Geeks With Blogs

News Ashraful Alam Joy

Create Your Badge

Ashraful Alam is a Software Architect, who has 8 years of professional experience in Software Development industry. This Bangladeshi national is involved with project management and development of several US based software projects from his country. Already he has managed and developed several software projects, which are being used by several users of different countries, such as USA, Canada, Australia, and Bangladesh. While developing and managing a team, he contains and maintains a set of well defined engineering practices developed by him and other online developer communities.

Due to his willingness to give effort to improve and share better software development practices, Ashraf has been awarded as “Most Valuable Professional” (MVP) in ASP.NET category by Microsoft since year 2007 multiple times, which is a rare honor and prestigious reorganization among the developers around the world.

Check his portfolio to know more about him and his works.


.NETTER Characters... Every part of your life is best, if you can know yourself and thus create your life like an artist!
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.

Posted on Friday, February 15, 2008 2:47 PM | Back to top


Comments on this post: Simple C# Delegate Sample

# 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

# re: Simple C# Delegate Sample
Requesting 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
Left by Swathi on Nov 25, 2008 3:26 PM

# re: Simple C# Delegate Sample
Requesting 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");
}
}
Left by umesh on Dec 03, 2008 12:25 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
salim benbahmed's explanation is the *only* one that makes any kind of sense.
Left by JustThisGuy on Dec 03, 2008 3:48 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Nice explanation
Left by Sam on Jan 06, 2009 10:50 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Salim - Your explanation does make sense. IT really helped in understading the delegate concept witn an easy example.

Thanks for your inputs....
Left by He - man! on Jan 15, 2009 3:56 AM

# re: Simple C# Delegate Sample
Requesting 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
Left by He - man! on Jan 15, 2009 3:58 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Examples, examples, examples, talk is cheap... Let's see it demonstrated in a useful scenario !
Left by joedotnot on Jan 26, 2009 4:30 PM

# re: Simple C# Delegate Sample
Requesting 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. :)
Left by J on Feb 17, 2009 5:30 AM

# re: Simple C# Delegate Sample
Requesting 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)...

:)
Left by J on Feb 17, 2009 5:41 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Delegates are used extensively in threading applications.

Without them it's difficult to execute cross thread operations.
Left by carl on Mar 07, 2009 3:31 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Thank you for this information.
It was very helpful for a university project i am working on.
Left by Joao on Mar 30, 2009 9:17 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Thanks .. its really easy to follow
Left by ani on May 21, 2009 7:11 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
what's the use of delegate & where to use it & to differentiate it from others..
Left by sureka on Jun 09, 2009 8:37 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Thanks for the easy example it is easy to grasp. Example given by J helps to understand practical scenerio
Left by sweeny on Jun 13, 2009 12:53 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Thank you very much for this wonderful explanation!
Left by Scott on Jun 24, 2009 11:57 AM

# re: Simple C# Delegate Sample
Requesting 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!
Left by Russ on Aug 14, 2009 7:37 AM

# re: Simple C# Delegate Sample
Requesting 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.
Left by James K on Sep 08, 2009 10:50 AM

# re: Simple C# Delegate Sample
Requesting 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.
Left by C# Chick on Nov 30, 2009 4:08 PM

# re: Simple C# Delegate Sample
Requesting 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...
Left by Prasanna on Jan 28, 2010 6:52 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Thank you very much. Very simple, perfect.

Cheers,
Dave
Left by Dave on Feb 08, 2010 5:25 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
If you've used C++, think Function Pointer :)
Left by Steve on Feb 19, 2010 12:27 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
In my opinion , its very good example and concept for beginers like me. But now could you help me about delegate in deep.
Left by neelam on Mar 30, 2010 5:46 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
TO----Prasanna

YA u r rite.. it shoulf be Display(string S)
Left by vighnu on Jul 01, 2010 4:18 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
It's a very good example.Plz define the deeply throw class step by step
Left by Sankalp Shrivastava on Jul 22, 2010 4:20 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Thanks dude,ur codes sounds very nice.. really i got.Could u explain the Delegates with events in the Same way..
Left by Suresh S on Jul 27, 2010 10:26 PM

# re: Simple C# Delegate Sample
Requesting 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
Left by AJ on Aug 02, 2010 1:29 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
its good for understanding
Left by krishna on Aug 12, 2010 7:25 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
its good and easy for understanding
Left by krishna on Aug 12, 2010 7:25 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
hmmm very nice article....& its help me a lot..! thnnx :)
Left by Ananda on Sep 03, 2010 7:57 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Thank You; Its really nice explanation
Left by Sailaja on Sep 14, 2010 7:32 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
am a beginner in c# can u plzz help lemme know which book is better to refer
Left by shilka on Oct 22, 2010 5:21 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
I appreciate. it really was simple and valuable
Left by ahmad on Nov 21, 2010 6:53 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
man be amizesh c# nyaz daram
Left by hossein on Jan 24, 2011 6:11 PM

# re: Simple C# Delegate Sample
Requesting 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. :)
Left by Captain Awesome on Mar 18, 2011 4:09 AM

# re: Simple C# Delegate Sample
Requesting 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
Left by Rafi on Apr 01, 2011 3:20 AM

# Thanks for the sample
Requesting Gravatar...
Dear,
I found your sample answer so useful for me. thnks for the sample example.... I really got my answer through this post.
Left by Kulsurya on Oct 03, 2011 11:10 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
nice n easy to understand.........i hope so :)
Left by greens on Oct 18, 2011 12:11 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Fantastic example. I was confused about delegate.But your example helps me lot to understand well. It was clear. Thank you so much
Left by sudha on Nov 02, 2011 8:18 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
thank's, is was very usefull for me.
Left by amyrh on Nov 05, 2011 12:37 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Good and simple...
Left by Prakash NB on Nov 14, 2011 1:30 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Sir,
I like your link very much

but i am join to you please for future guidence
Left by jitendra kumar kannaujiya on Nov 26, 2011 11:36 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Thanks !
Left by noman on Nov 30, 2011 2:15 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
simple and elegant
Left by babu on Dec 02, 2011 5:36 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Thanks for clearing my concepts.
Left by Vikas on Dec 12, 2011 5:49 PM

# re: Simple C# Delegate Sample
Requesting Gravatar...
Very nice article..really helpful.
Can any1 give a link where delegates are explained in more deep..
hope to see the rply...:)
Left by Mayuri on Jan 10, 2012 7:35 AM

# re: Simple C# Delegate Sample
Requesting Gravatar...
I got the idea. nice post... thanks
Left by Krishna on Jan 10, 2012 10:35 AM

Your comment:
 (will show your gravatar)


Copyright © Ashraf Alam | Powered by: GeeksWithBlogs.net | Join free