Simple C# Delegate Sample

New developers often ask me about C# delegate, as they got a bit confused about the basic concept and specially maximum of the reference contains and discussed from an advanced view. Well I think delegate is really simple, when you grab it's basic idea.

So what is delegate?

Basically it is similar like the old "C" age function pointer, where functions can be assigned like a variable and called in the run time based on dynamic conditions. C# delegate is the smarter version of function pointer which helps software architects a lot, specially while utilizing design patterns.

At first, a delegate is defined with a specific signature (return type, parameter type and order etc). To invoke a delegate object, one or more methods are required with the EXACT same signature. A delegate object is first created similar like a class object created. The delegate object will basically hold a reference of a function. The function will then can be called via the delegate object.

Sounds easy? If not lets have a look in the code snippets below.

1. Defining the delegate

public delegate int Calculate (int value1, int value2);

2. Creating methods which will be assigned to delegate object

//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegate
public int add(int value1, int value2)
{
    return value1 + value2;            
}
//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegate
public int sub( int value1, int value2)
{
    return value1 - value2;            
}

3. Creating the delegate object and assigning methods to those delegate objects

//creating the class which contains the methods 
//that will be assigned to delegate objects
MyClass mc = new MyClass();

//creating delegate objects and assigning appropriate methods
//having the EXACT signature of the delegate
Calculate add = new Calculate(mc.add);
Calculate sub = new Calculate(mc.sub);

4. Calling the methods via delegate objects

//using the delegate objects to call the assigned methods 
Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));

Pretty simple, huh? Happy coding!!

Download source code:

kick it on DotNetKicks.com

Print | posted on Friday, February 15, 2008 2:47 PM

Comments on this post

# re: Simple C# Delegate Sample

Requesting Gravatar...
Exactly, whats the use of them except making things less elegant
Left by Name on Jun 15, 2008 2:53 AM

# re: Simple C# Delegate Sample

Requesting Gravatar...
My question is same as the first comment...Whats the benefit or cause to use delegates and when to use this...


u may mail me....
faysal_002299 [attt] y a h o o [dotttt] com


thanks for the post
Faysal
Left by Faysal on Jun 25, 2008 12:33 PM

# re: Simple C# Delegate Sample

Requesting Gravatar...
you use them when you have too! ;-)

for exemple you use them for events.

you can use them in place of an interface, when all you need is 1 function, for exemple:
List<T>.Sort(Comparison<T> cmp)
List<T>.Find(Predicate<T> p)
Left by Lloyd Dupont on Jul 26, 2008 8:45 AM

# re: Simple C# Delegate Sample

Requesting Gravatar...
i agree with ming.
it pretty much looks the same.
can anyone tell me where can a delegate be useful?
Left by Lordan on Aug 17, 2008 9:52 AM

# re: Simple C# Delegate Sample

Requesting Gravatar...
ooh man is the BeginInvoke and asyncronous calls
Left by sergio ivan on Aug 20, 2008 12:35 AM

# re: Simple C# Delegate Sample

Requesting Gravatar...
I had the same question m8. Why bother with the delegate. It seems like creating a class called MyMath then 2 functions (add/sub) would do the same thing. The only reason to make it a class is to keep the logic seperate from the design. Other than that... why a delegate?

I'm still not seeing why it's usefull. And don't even get me started on Interfaces instead of Classes.
Left by JoeUser on Aug 20, 2008 9:56 PM

# re: Simple C# Delegate Sample

Requesting Gravatar...
Thanks , Your post helps me a lot. A stuck in a silly situation. Your post helps me on that.
Left by Devbrat Ghosh on Oct 06, 2008 5:52 PM

# re: Simple C# Delegate Sample

Requesting Gravatar...
Let say I write a class that checks for stock prices and sends an alert when the stocks go above or below a threshold. This could take days or months (perhaps not these days though).

Now you write code and want to be notified.
You could call my method repeatedly (say every five minutes and check).

The alternative is to call my method and pass me your method so that I can call it when the event of interest occurs.

That way, you call me once, pass me your method and forget about it. When the event occurs, you will get notified.

Those are the kind of things delegates are good for.

Salim.
Left by salim benbahmed on Oct 17, 2008 5:32 AM

# re: Simple C# Delegate Sample

Requesting Gravatar...
Another good example is, for instance you have the code as like ---

Statement 1
Statement 2
Statement 3
METHOD X
Statement 4
Statement 5
Statement 6

Now, you have similar structure for several method call, t(i.e. to have the SAME statement from Statement 1 - 6).

In that case you can reduce your code, just the passing methods as delegate object, when you need to run the statements for that method!

Hope this helps!!
Left by Ashraful Alam on Nov 07, 2008 3:37 PM

Your comment:

 (will show your gravatar)
 
Please add 2 and 4 and type the answer here: