Monday, March 12, 2012

Why use delegates?

I wrote the following code to help me understand delegates.
I understand them technically but not WHEN and WHY I would use them in my own code.

More precisely, it seems from this example that using delegates just seems to make simple code more complicated, i.e. you have to go through extra programming steps which don't give you any added value.

using System;
using System.Collections.Generic;
using System.Text;

class Program
{
static void Main(string[] args)
{
Mathematician mathematican =new Mathematician();
DelegateMathematician delegateMathematician =new DelegateMathematician();
}
}

class Mathematician
{
public Mathematician()
{
Console.WriteLine("10 plus 20 = {0}", AddNumbers(10, 20));
Console.WriteLine("10 times 20 = {0}", MultiplyNumbers(10, 20));
Console.WriteLine();
}

private int AddNumbers(int a,int b)
{
return a + b;
}

private int MultiplyNumbers(int a,int b)
{
return a * b;
}
}

class DelegateMathematician
{
public delegate int Equation(int a,int b);

public DelegateMathematician()
{
Equation adder =new Equation(this.AddNumbers);
Equation multiplier =new Equation(this.MultiplyNumbers);

Console.WriteLine("The delegate that adds says about 10 and 20: {0}", adder(10, 20));
Console.WriteLine("The delegate that multiplies says about 10 and 20: {0}", multiplier(10, 20));
Console.WriteLine();
}

private int AddNumbers(int a,int b)
{
return a + b;
}

private int MultiplyNumbers(int a,int b)
{
return a * b;
}

}

Delegates are basically pointers to functions my friend.

I have used them in several cases when some of my classes raise events and multiple events can respond to the same event in different ocassions.

In C# every event creates a delegate, i.e: delegate to handle the click event of a button.

These are not required everytime, so you don´t need to add complexity to your application.


There is much to say about Delegates but I will give you the real life scenario.

Suppose you are running a newspaper and you have 3 subscribers. Everytime a new newspaper comes they get the paper since they are subscribers. Delegates are pretty much like that, you subscribe methods to the delegates which consists of a particular signature. Now, delegate can send a message to all the methods who are subscribed to it.


Some more in:

http://www.ondotnet.com/pub/a/dotnet/2002/11/04/delegates.htm

http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=141

http://www.expresscomputeronline.com/20021216/techspace2.shtml

Hope it helps!


In your example the event is "create newsletter" and you might have 10 methods which subscribe to this. But you need an event of some kind. Is it true that delegates only make sense in terms of events? For example, how could I add events to my example above?

0 comments:

Post a Comment