Exforsys.com
 

Sponsored Links

 

C Sharp Tutorials

 
Home Tutorials C Sharp
 

Delegates in C#

 

Delegates in C#

Most programmers are used to passing data in methods as input and output parameters.
Imagine a scenario where you wish to pass methods around to other methods instead of data. Amazed! Read further.



Consider a scenario where you need to make a ‘business decision’ in your program, to make a decision you need data. To get data you need to call a method. However the method name is not known at design time. It will only be known at run time.


In this case you need to pass the unknown method as a parameter. The method that you are passing in is known as a Callback function. Call back functions are pointers to methods.


.NET implements the concept of function pointers using delegates.


  • Delegate wraps a method. Calling delegate results in calling the method.
  • Delegate is a type of object very similar to classes.
  • Delegate gives a name to a method signature.

Where are Delegates used?

The most common example of using delegates is in events.


You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place.


This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.


Starting Threads/Parallel Processing:

You defined several methods and you wish to execute them simultaneously and in parallel to whatever else the application is doing. This can be achieved by starting new threads. To start a new thread for your method you pass your method details to a delegate.


Generic Classes: Delegates are also used for generic class libraries which have generic functionality defined. However the generic class may need to call certain functions defined by the end user implementing the generic class. This can be done by passing the user defined functions to delegates.


Creating and Using Delegates:

Using delegates is a two step process-
..........1) Define the delegate to be used
..........2) Create one or more instances of the delegate
Syntax for defining a delegate:


delegate string reviewStatusofARegion();


to define a delegate we use a key word delegate followed by the method signature the delegate represents. In the above example string reviewStatusofARegion(); represents any method that returns a string and takes no parameters.


Syntax for creating an instance of the delegate:


reviewStatusofARegion = new reviewStatusofARegion(myClass.getEurope)


private string getEurope()
{
return “Doing Great in Europe”;
}


To create an instance of the delegate you call its constructor. The delegate constructor takes one parameter which is the method name.


The method signature should exactly match the original definition of the delegate. If it does not match the compiler would raise an Error.


Multicast Delegate:
Delegate wraps a method. Calling delegate results in calling the method. It is possible to wrap more than one method in a delegate. This is known as a multicast delegate.

If you make a call to a multicast delegate it will call all the functions it wraps in the order specified. Please note that functions in this case should not return any values.
Syntax for defining a delegate:
delegate void deleteRowsinTable( int Year)

Syntax for instantiating the delegate:
deleteRowsinTable Cleanup = new deleteRowsinTable(archiveCompletedTasks)

Cleanup += new deleteRowsinTable(purgeCompletedTasks)

Using Delegates in Event Handling
Events could be visualized as following:




Example: You setup a wakeup alarm in your clock for 6 a.m.



Hence you need a class/object that creates and fires an event
You need a mechanism to notify all
You need a method to listen for the notification
Finally, you need a method that does something when the notification is received.

Another example


Here is how you code for it

Create a class called Mylist
1) Declare an Event public event System.EventHandler EventName;
2) Declare a method that creates the event protected virtual void OnEventName(System.EventArgs e) 3) Fire the Event when appropriate conditions are met by calling the above method
If (condition met) {protected virtual void OnEventName(System.EventArgs e);}



Now you have a class that has the event definition, triggers an event when appropriate condition occurs and notifies every one.

Next, Create a class EventListener
1) Create a variable of type MyList
2) Create a method that shows a message box
3) Create constructor which takes a parameter of type MyList
4) In the constructor add the method you created in step 2 as an eventhandler for the event ( See Code below)
5) Add a method to remove the method from the event handler





Now you have a class that handles the event and does something when the even occurs




Next, create a class in a console application to test all of the above
1) Create an instance of the list
2) Create the event handler
3) Add an Item to the list
4) See the Results



 


The results shown below



Summary:


In this article we studied the basics of delegates and Event handling in C#



Read Next: Building Web Based N-Tier Applications using C#



 

 

Comments


prasadlaskhmi said:

  :) nice articl..i got some information regarding delogates and events.. thnq very much..pls..keep on..going..
July 20, 2006, 2:10 pm

divya22 said:

  the topic about the events is very gud and easily understandable.
thanq
November 11, 2006, 10:35 am

Tomasz said:

  Straightforward and clear explanation delegates ideas.
February 16, 2007, 11:11 am

dany said:

  easy to understand and to the point... good for new comers like me
May 17, 2007, 6:13 am

Take 9 said:

  I get it! it all makes sense!
May 29, 2007, 9:21 pm

Jamal Ahmad said:

  That will help programmers alot.
June 30, 2007, 2:12 am

yyc said:

  Most of the articles that I read are of bullshit, it delivers nothing. But yours is different, you make the point clear with a simple console program that even a newbie can understand easily. Keep it up!
July 22, 2007, 5:35 am

praveen.b said:

  GOOD .. we can understand it easily ,if u add some more examples it ll be so useful
August 2, 2007, 1:27 am

Amit_K said:

  Can say one of the rare articles that elaborates point to point about Deligates.
August 9, 2007, 6:31 am

shreesjce said:

  Easy to understand..
September 5, 2007, 4:03 am

Vinay Ramamurthy said:

  Very Very Good...explains everything about delegates....
November 6, 2007, 8:16 am

Md Salman Arafath said:

  Give more examples starting from the simple example slowly introduce complexity in simple manner.
Let simple thing be simple and complex things are possible
November 8, 2007, 4:23 am

Saheed NIGERIA said:

  This is great quite understanding ,am newbie in C# and i feel it down to brain ,and applying it .IT WORKS!!!!!!!!.
November 10, 2007, 3:52 am

chrstina said:

  yeah,,i underatand it , thank you very much, and go on please ....great work
November 20, 2007, 12:38 pm

Umer said:

  thats a good article
December 24, 2007, 5:31 am

kumarchand said:

  It is very easy and simple to understand. Can you please give the more clear information about what is the relationship between the delegates and events.
January 7, 2008, 6:14 am

micahadarayan said:

  Very Nice, please send me this article, I relly like it. Tnx!
March 6, 2008, 9:51 pm

Deeparamsy said:

  easy to understand...helped me understand delegats...thank u..
March 11, 2008, 4:53 am

Paramjeet said:

  Really very nice explanation. Very helping for a new programmer to understand the idea. Its good you didn't start with explaining that delegates are like c pointers to functions, not everyone remember the C which was learned at school time.
July 18, 2008, 5:09 am

cjarlioe said:

  I'm working on a program that delegates everything... I cant find the use for delegates. It's a very abstract concept
July 23, 2008, 7:39 pm

Meganadha Reddy K. said:

  Thanks a lot for a very good article
August 27, 2008, 1:12 am

kien said:

  Is a very good article. Can you explained more how the delegate work on memory side?
November 13, 2008, 9:50 pm

vivek said:

  very good article...superb
December 18, 2008, 2:26 am

prashant gindt said:

  u should ask the viewer to try a few good questions , so that the viewer may apply his grey to reach the bottom of the topic.

good questions are as necessary as a good study.
December 30, 2008, 12:06 pm

vinod gupta said:

  good article
January 19, 2009, 6:29 am

Sunidhi Sharma said:

  Its an Excellent article. It clear almost queries about delegates and events . But it will be very thankful to you if you more clear how to use delegate and how it help us in increasing the performance of the events in asp.net event handler by sending me mail.
thanx
February 17, 2009, 2:39 am

Anand Shanbhag said:

  Very well explained. I was trying to understand this concept from couple of days but to no use. After reading your article, I am really confident.In Short, it was crystal clear.
Thanks!
June 17, 2009, 1:10 am

Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 

Subscribe via RSS


Get Daily Updates via Subscribe to Exforsys Free Training via email


Get Latest Free Training Updates delivered directly to your Inbox...

Enter your email address:


 

Subscribe to Exforsys Free Training via RSS
 

 
Partners -  Privacy and Legal Policy -  Site News -  Contact   Sitemap  

Copyright © 2000 - 2009 exforsys.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape