alt
Advertisement
Sponsored links
Online Training
Career Series
Exforsys
Exforsys arrow Tutorials arrow C# arrow Delegates in C#
Site Search


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#


Trackback(0)
Comments (16)add comment

Tomasz said:

  Straightforward and clear explanation delegates ideas.
February 16, 2007

dany said:

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

Take 9 said:

  I get it! it all makes sense!
May 29, 2007

Jamal Ahmad said:

  That will help programmers alot.
June 30, 2007

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

praveen.b said:

  GOOD .. we can understand it easily ,if u add some more examples it ll be so useful
August 02, 2007

Amit_K said:

  Can say one of the rare articles that elaborates point to point about Deligates.
August 09, 2007

shreesjce said:

  Easy to understand..
September 05, 2007

Vinay Ramamurthy said:

  Very Very Good...explains everything about delegates....
November 06, 2007

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 08, 2007

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

chrstina said:

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

Umer said:

  thats a good article
December 24, 2007

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 07, 2008

micahadarayan said:

  Very Nice, please send me this article, I relly like it. Tnx!
March 06, 2008

Deeparamsy said:

  easy to understand...helped me understand delegats...thank u..
March 11, 2008

Write comment

busy
 
< Prev   Next >
Exforsys Offers
© 2008 Exforsys.com
Joomla! is Free Software released under the GNU/GPL License.
Page copy protected against web site content infringement by Copyscape