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.

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

Feedback

# re: Simple C# Delegate Sample

left by Name at 6/15/2008 2:53 AM Gravatar
Exactly, whats the use of them except making things less elegant

# re: Simple C# Delegate Sample

left by Faysal at 6/25/2008 12:33 PM 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

# re: Simple C# Delegate Sample

left by Lloyd Dupont at 7/26/2008 8:45 AM 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)

# re: Simple C# Delegate Sample

left by Lordan at 8/17/2008 9:52 AM Gravatar
i agree with ming.
it pretty much looks the same.
can anyone tell me where can a delegate be useful?

# re: Simple C# Delegate Sample

left by sergio ivan at 8/20/2008 12:35 AM Gravatar
ooh man is the BeginInvoke and asyncronous calls

# re: Simple C# Delegate Sample

left by JoeUser at 8/20/2008 9:56 PM 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.

# re: Simple C# Delegate Sample

left by Devbrat Ghosh at 10/6/2008 5:52 PM Gravatar
Thanks , Your post helps me a lot. A stuck in a silly situation. Your post helps me on that.

# re: Simple C# Delegate Sample

left by salim benbahmed at 10/17/2008 5:32 AM 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.

# re: Simple C# Delegate Sample

left by Ashraful Alam at 11/7/2008 3:37 PM 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!!

# re: Simple C# Delegate Sample

left by Swathi at 11/25/2008 3:26 PM Gravatar
suppose the code is like...
class MyClass
public static void Display(int S)
{
System.Console.WriteLine("This is Display called" +S);
}
public static void Main(string []args)
{
public delegate void Del_One(String S);
Del_One del_Obj=new Del_One(Diaplay);
del_Obj("Dilshuknagar");

CAn you tell mee what is the error in this program

# re: Simple C# Delegate Sample

left by umesh at 12/3/2008 12:25 AM Gravatar
You can not define delegate insite function.
Declare it at class level. And also use "Display" instead of "diaplay" in function assignment in delgate


class MyClass{
public delegate void Del_One(String S);

public static void Display(int S)
{
System.Console.WriteLine("This is Display called" +S);
}
public static void Main(string []args)
{
Del_One del_Obj=new Del_One(Display);
del_Obj("Dilshuknagar");
}
}

# re: Simple C# Delegate Sample

left by JustThisGuy at 12/3/2008 3:48 PM Gravatar
salim benbahmed's explanation is the *only* one that makes any kind of sense.

# re: Simple C# Delegate Sample

left by Sam at 1/6/2009 10:50 AM Gravatar
Nice explanation

# re: Simple C# Delegate Sample

left by He - man! at 1/15/2009 3:56 AM Gravatar
Salim - Your explanation does make sense. IT really helped in understading the delegate concept witn an easy example.

Thanks for your inputs....

# re: Simple C# Delegate Sample

left by He - man! at 1/15/2009 3:58 AM Gravatar
Therefore, it looks like it is usefull in the asyncronous calls....where we don't know when exactly the condition will trigger....

He-man

# re: Simple C# Delegate Sample

left by joedotnot at 1/26/2009 4:30 PM Gravatar
Examples, examples, examples, talk is cheap... Let's see it demonstrated in a useful scenario !

# re: Simple C# Delegate Sample

left by J at 2/17/2009 5:30 AM Gravatar
public class MyDbClass
{
public delegate void _loadMethod(int uid);

public _loadMethod Load;

private SqlLoad(int uid)
{
//Do something specific to Sql here
}

private OleLoad(int uid)
{
//Do something specific to Ole here
}

public MyDbClass(string Provider)
{
if ( Provider.Equals("Sql"))
Load = new _loadMethod(SqlLoad);
else
Load = new _loadMethod(OleLoad);
}
}

This is rough and untested. I'm still grappling with delegates myself, but there are plenty of uses for them.
In my example, the Database provider can be determined at run time and any features specific to that provider can be utilised by having a seperate method for each.
By using a delegate in this scenario, the rest of your code only ever needs to call MyDbClass.Load(...);

I'm only just learning C#. Corrections are always welcome. :)

# re: Simple C# Delegate Sample

left by J at 2/17/2009 5:41 AM Gravatar
oops. Just realised I forgot to put in a return type on the SqlLoad and OleLoad methods.

private void SqlLoad(int uid)...
and
private void OleLoad(int uid)...

:)

# re: Simple C# Delegate Sample

left by carl at 3/7/2009 3:31 AM Gravatar
Delegates are used extensively in threading applications.

Without them it's difficult to execute cross thread operations.

# re: Simple C# Delegate Sample

left by Joao at 3/30/2009 9:17 PM Gravatar
Thank you for this information.
It was very helpful for a university project i am working on.

# re: Simple C# Delegate Sample

left by ani at 5/21/2009 7:11 PM Gravatar
Thanks .. its really easy to follow

# re: Simple C# Delegate Sample

left by sureka at 6/9/2009 8:37 PM Gravatar
what's the use of delegate & where to use it & to differentiate it from others..

# re: Simple C# Delegate Sample

left by sweeny at 6/13/2009 12:53 PM Gravatar
Thanks for the easy example it is easy to grasp. Example given by J helps to understand practical scenerio

# re: Simple C# Delegate Sample

left by Scott at 6/24/2009 11:57 AM Gravatar
Thank you very much for this wonderful explanation!

# re: Simple C# Delegate Sample

left by Russ at 8/14/2009 7:37 AM Gravatar
A lot of people seem to struggle with why interfaces and delegates exists in the first place. The reason becomes apparent when you start passing objects in your code. By using classes, interfaces, and delegates, you make your code type safe. So why not just always use classes... because thats the "whole kitchen sink" and the accepting object very rarely need to know everything about the object being passed to it. That is why there are interfaces... it allows you to pass a specific set of properties/methods. And if you only need a specific method passed... that is what a delegate is for. That is the CONCEPT. This concept is the foundation for all the OO development patterns around passing objects between objects. Hope this helps!

# re: Simple C# Delegate Sample

left by James K at 9/8/2009 10:50 AM Gravatar
Imgaine you have a GUI form - When the user clicks a button it creates some class and calls a method on this class which does some work (say 50 tasks)? Supposing you wanted to report back to the GUI how the progress is going. You could just call some function on the GUI to check every five minutes, however using a delegate you could report back the progress after each job completes.

# re: Simple C# Delegate Sample

left by C# Chick at 11/30/2009 4:08 PM Gravatar
While the post helped to clear up how to use delegates in C#, thanks to everyone for the great questions and comments that helped to clear up in my mind why you use delegates. I have been reading several blog posts and have had a hard time finding good explanations.

# re: Simple C# Delegate Sample

left by Prasanna at 1/28/2010 6:52 PM Gravatar
am sorry ... am in process of learning delecate's .. i read this article fully.. in the comments section..
one of a friend posted

class MyClass{
public delegate void Del_One(String S);

public static void Display(int S)
{
System.Console.WriteLine("This is Display called" +S);
}
public static void Main(string []args)
{
Del_One del_Obj=new Del_One(Display);
del_Obj("Dilshuknagar");
}
}


since delegates are type safe as mentioned in the article " a delegate is defined with a specific signature (return type, parameter type and order etc)"
and in the above code it has diff parameter data types
" public delegate void Del_One(String S);

public static void Display(int S) "

aint these two contradictory ...

kindly clear it as am in the art of learning ... will be helpful to understand better... thanks...

# re: Simple C# Delegate Sample

left by Dave at 2/8/2010 5:25 AM Gravatar
Thank you very much. Very simple, perfect.

Cheers,
Dave

# re: Simple C# Delegate Sample

left by Steve at 2/19/2010 12:27 PM Gravatar
If you've used C++, think Function Pointer :)

# re: Simple C# Delegate Sample

left by neelam at 3/30/2010 5:46 PM Gravatar
In my opinion , its very good example and concept for beginers like me. But now could you help me about delegate in deep.

# re: Simple C# Delegate Sample

left by vighnu at 7/1/2010 4:18 AM Gravatar
TO----Prasanna

YA u r rite.. it shoulf be Display(string S)

# re: Simple C# Delegate Sample

left by Sankalp Shrivastava at 7/22/2010 4:20 PM Gravatar
It's a very good example.Plz define the deeply throw class step by step

# re: Simple C# Delegate Sample

left by Suresh S at 7/27/2010 10:26 PM Gravatar
Thanks dude,ur codes sounds very nice.. really i got.Could u explain the Delegates with events in the Same way..

# re: Simple C# Delegate Sample

left by AJ at 8/2/2010 1:29 AM Gravatar
Hi,

If your main() is 'static' then all other methods should be 'static', so that you can call all the methods inside the main() without creating object. If you don't want to use static methods, then you have to create the object of the class in Main(), then you can call the non-static mentods.
Eg : Static Methods
class Program
{
public delegate int TestDele(string input);

public static int dispdata(string input)
{
Console.WriteLine("Delegate example\n");
Console.WriteLine("User Input:"+input+"\n");
return 0;
}
static void Main(string[] args)
{
string test=null;
if (args.Length > 0)
{
test = args[0];
TestDele dele = new TestDele(dispdata);
dele(test);
}

}
}

Non- static methods ( Except main())
class Program
{
public delegate int TestDele(string input);

public int dispdata(string input)
{
Console.WriteLine("Delegate example\n");
Console.WriteLine("User Input:"+input+"\n");
return 0;
}
static void Main(string[] args)
{
string test=null;
if (args.Length > 0)
{
test = args[0];
Program cls = new Program();
TestDele dele = new TestDele(cls.dispdata);
dele(test);
}

}
}
Hope it will be useful for you.

- http://www.aloysiusjegan.in

# re: Simple C# Delegate Sample

left by krishna at 8/12/2010 7:25 PM Gravatar
its good for understanding

# re: Simple C# Delegate Sample

left by krishna at 8/12/2010 7:25 PM Gravatar
its good and easy for understanding

# re: Simple C# Delegate Sample

left by Ananda at 9/3/2010 7:57 PM Gravatar
hmmm very nice article....& its help me a lot..! thnnx :)

# re: Simple C# Delegate Sample

left by Sailaja at 9/14/2010 7:32 PM Gravatar
Thank You; Its really nice explanation

# re: Simple C# Delegate Sample

left by shilka at 10/22/2010 5:21 PM Gravatar
am a beginner in c# can u plzz help lemme know which book is better to refer

# re: Simple C# Delegate Sample

left by ahmad at 11/21/2010 6:53 PM Gravatar
I appreciate. it really was simple and valuable

# re: Simple C# Delegate Sample

left by hossein at 1/24/2011 6:11 PM Gravatar
man be amizesh c# nyaz daram

# re: Simple C# Delegate Sample

left by Captain Awesome at 3/18/2011 4:09 AM Gravatar
You use it when you have to, which is not very often. But trying to do something in one window after clicking a button in another window, Visual Studio says I have to use a delegate. :)

# re: Simple C# Delegate Sample

left by Rafi at 4/1/2011 3:20 AM Gravatar
Thanks very much, i learned a lot of delegates examples but could not go with that.

Thanks for your simple example and code..

Thanks Thanks thanks man
6DWS

# Thanks for the sample

left by Kulsurya at 10/3/2011 11:10 AM Gravatar
Dear,
I found your sample answer so useful for me. thnks for the sample example.... I really got my answer through this post.

# re: Simple C# Delegate Sample

left by greens at 10/18/2011 12:11 AM Gravatar
nice n easy to understand.........i hope so :)

# re: Simple C# Delegate Sample

left by sudha at 11/2/2011 8:18 PM Gravatar
Fantastic example. I was confused about delegate.But your example helps me lot to understand well. It was clear. Thank you so much

# re: Simple C# Delegate Sample

left by amyrh at 11/5/2011 12:37 PM Gravatar
thank's, is was very usefull for me.

# re: Simple C# Delegate Sample

left by Prakash NB at 11/14/2011 1:30 PM Gravatar
Good and simple...

# re: Simple C# Delegate Sample

left by jitendra kumar kannaujiya at 11/26/2011 11:36 AM Gravatar
Sir,
I like your link very much

but i am join to you please for future guidence

# re: Simple C# Delegate Sample

left by noman at 11/30/2011 2:15 PM Gravatar
Thanks !

# re: Simple C# Delegate Sample

left by babu at 12/2/2011 5:36 PM Gravatar
simple and elegant

# re: Simple C# Delegate Sample

left by Vikas at 12/12/2011 5:49 PM Gravatar
Thanks for clearing my concepts.

# re: Simple C# Delegate Sample

left by Mayuri at 1/10/2012 7:35 AM Gravatar
Very nice article..really helpful.
Can any1 give a link where delegates are explained in more deep..
hope to see the rply...:)

# re: Simple C# Delegate Sample

left by Krishna at 1/10/2012 10:35 AM Gravatar
I got the idea. nice post... thanks
Post A Comment
Title:
Name:
Email:
Comment:
Verification: