Sponsored Links
C Sharp Tutorials
- Structural and Behavioral Design Patterns
- Creational Design Patterns
- Software Architecture & Design Patterns
- C# Language Basics
- . NET Type Safety
- Regular Expressions in C# - Quantifiers and Delegates
- Regular Expressions and C#, .NET
- .NET Remoting
- Inheritance in C#
- Delegates in C#
- Building Web Based N-Tier Applications using C#
Tutorials
C SharpDelegates 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#
Comments
prasadlaskhmi said:
| :) nice articl..i got some information regarding delogates and events.. thnq very much..pls..keep on..going.. |
divya22 said:
|
the topic about the events is very gud and easily understandable. thanq |
Tomasz said:
| Straightforward and clear explanation delegates ideas. |
dany said:
| easy to understand and to the point... good for new comers like me |
Take 9 said:
| I get it! it all makes sense! |
Jamal Ahmad said:
| That will help programmers alot. |
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! |
praveen.b said:
| GOOD .. we can understand it easily ,if u add some more examples it ll be so useful |
Amit_K said:
| Can say one of the rare articles that elaborates point to point about Deligates. |
shreesjce said:

| Easy to understand.. |
Vinay Ramamurthy said:
| Very Very Good...explains everything about delegates.... |
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 |
Saheed NIGERIA said:
| This is great quite understanding ,am newbie in C# and i feel it down to brain ,and applying it .IT WORKS!!!!!!!!. |
chrstina said:
| yeah,,i underatand it , thank you very much, and go on please ....great work |
Umer said:
| thats a good article |
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. |
micahadarayan said:
| Very Nice, please send me this article, I relly like it. Tnx! |
Deeparamsy said:
| easy to understand...helped me understand delegats...thank u.. |
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. |
cjarlioe said:
| I'm working on a program that delegates everything... I cant find the use for delegates. It's a very abstract concept |
Meganadha Reddy K. said:
| Thanks a lot for a very good article |
kien said:
| Is a very good article. Can you explained more how the delegate work on memory side? |
vivek said:
| very good article...superb |
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. |
vinod gupta said:
| good article |
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 |
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! |
Sponsored Links
