posted 7/14/2010 by Hajan Selmani
Short intro
Many developers have already written some blog posts or articles regarding this subject. In the following blog, I will try to explain the concepts of using Events and Delegates in C#.NET and will try to keep it as simpler as possible, in order to give clear view to all those who are confused, especially about delegates.
The first time I’ve started learning about C#.NET from its very first version, the first new thing for this programming language I heard is that it does not uses pointers and references. From the university days as a student, I’ve started with C++. Once I learnt the Pointers and References, I get used to work a lot with them, so I was confused why C# does not uses pointers. Then, after reading my first book about C#, I’ve noticed that there are delegates that replaces the functionality of pointers. And, after testing some scenarios, it came out that delegates are very interesting and great thing introduced in C# that can be used for some specific cases.
Events and Delegates
The simplest and most important thing we should know is that Events are declared by using Delegates.
Shortly, as the keyword refers, an Event is something that happens in a certain situation while the application runs. For instance, you have list of ‘things’ and you want an event to happen if new ‘thing’ is added to that list. More specifically, lets say you have an application that manages the opened documents. So if new document is opened, you want to fire an event.Another example would be, just add a control in your ASPX page or any .NET application, in the Properties go to the Events list. You will see various events that happen in a certain time while control is initiated, rendered, loaded, unloaded and so on. Then, you can create your own method related to any of these events, code that will run in that certain event when it will happen. The click event is well known to everyone because almost everyone have used it from the very beginning of programming in ASP.NET / C#.NET / VB.NET… So this event happens when the control is clicked. (I hope these examples are enough to help you understand the very basic theory of ‘events’).
Delegates is a concept (as I’ve mentioned previously) used since the beginning of C# language. If you know about methods, you can think of delegate as a method without type (see example bellow)
Example:
delegate void MyMethod();
So, this is completely same as if you have written as interface in the following way
interface MyInterface { void MyMethod(); }
Now, as I have mentioned methods previously – the connection between delegates and events are the methods, thus, the method that is implemented in your class to process and receive events is defined by the delegate itself. From this, we can conclude that the delegate defines what the event handler should return as well as what its parameter lists should be.
Complete example of usage Events and Delegates
In the following example, I have created custom event to fire whenever it finds number starting with 3 ending with 9 (counting to 10000).
//declaring the delegate public delegate void DelegateFoundNumber(int Number); class Numbers { public event DelegateFoundNumber NumberFound; public void FindNumber() { int c; for (c = 0; c <= 10000; c++) { if (c.ToString().StartsWith("3") && c.ToString().EndsWith("9")) { if (NumberFound != null) { NumberFound(c); } } } } } class EventHandlerClass { public void NeededNumberFound(int number) { Console.WriteLine(number); } } class MyMain { public static void Main() { Numbers MyNumb = new Numbers(); EventHandlerClass myEvtCls = new EventHandlerClass(); MyNumb.NumberFound += new DelegateFoundNumber(myEvtCls.NeededNumberFound); MyNumb.FindNumber(); } }
In the above example, I have created three classes: Numbers, EventHandlerClass and MyMain, and one delegate named as DelegateFounderNumber
Basically, Numbers class contains the declaration of the Event called NumberFound and a function FindNumber which is used to loop through the 10000 numbers and check for the first 3 and last 9 number.
Then, an EventHandlerClass that servers as the event handler for the Numbers class with using EventHandlerClass’s method NeededNumberFound, which is used to write the number.
The last MyMain class is the main class of the application itself. It simply calls the FindNumber() method of Numbers object. It first creates new instance of the delegate managing the NeededNumberFound from the EventHandlerClass and adds it to MyNumb object.
SIMPLY RUN THE CODE AND SEE THE RESULTS!!!
Conclusion
To sum up, you should have in mind that both Events and Delegates are used together, especially when you are going to create components that need to have some events in their functionality.
Moreover, I would like to note that:
… events are declared using delegates
… as we have seen in our example, fundamentially, events are just delegates - only the event keyword is literally just an access modifier which prevents code outside the class that declares the event from invoking the event.
… delegates are invoked by its clients once the event is fired.
… delegates are similar (I would say almost same) to C++ function pointers, but are type safe.
… delegates allow methods to be passed as parameters
I hope this was clear and helpful.
Best Regards,Hajan
This blog post was also posted on mkdot.net community blog:
http://mkdot.net/blogs/hajan/archive/2010/07/15/events-and-delegates-in-c-net.aspx
Hajan,
The way you have explained delegates and events is amazing!!
Earlier I tend to get confused about how to use it but now it is clear when and where to use it.
Keep writing interesting blogs like this.
Thanks.
Hajan still I have one question in my mind. Can you please tell me why you declared 'event = null' in constructor?
Thank you again Hajan:)
Hats off to you.
Keep writing and helping :)
This is "indeed" a great post! well presented. keep it up! =}
Thank you so much Hajan. Really it is very helpful for me and for who want to learn Delegate and events also.
It's my pleasure that u have written a blog on my request
Hey Hajan its a very nice and helpfull post, Thank you verymuch...!!! :)
I have posted this blog by request to one of the fellow members in CodeASP.NET Community - mohit, and I hope this was clear enough to help you understand the main concepts of events and delegates.
Please let me know your feedbacks.
this is a very good example..good work! Also, write some articles on anonymous functions too..another interesting topic...good work Hajan!
nice post
Guys, thank you for your comments! I really appreciate your thoughts!Mohit, for your last comment/question:The code inside constructor will run everytime the new object instance is created of the Numbers class. After that, as I have explained in the blog post:
Numbers MyNumb = new Numbers(); //1EventHandlerClass myEvtCls = new EventHandlerClass(); //2MyNumb.NumberFound += new DelegateFoundNumber(myEvtCls.NeededNumberFound); //3
when #1 runs, the constructor is called. It makes the NumberFound event null - clears all the references it contains to the delegates (there might be more than one delegates)
#2 we create instance myEvtCls (I've changed the name to shorer one)
#3 we connect the event with the method via delegate
in this case, if you delete the constructor, the code will run correctly. I have added this more as a concept I use :) - and also, firstly have been testing more complex solution and made it simpler in which we don't need the construcor, indeed. So, don't be confused about that ;).
I'm glad this was helpful.
Hajan Kindly check below post
http://codeasp.net/forums/asp-net-topics/getting-started-general-asp-net/475/delegates-and-events
@Sumit, your valuable comments give me stimulation to go further with contributing and writing blog posts like this one. Please, if you have any idea about any concept you would like to write about, post your thoughts. I have lots of things to write about, but I tend to go more with articles/blogs that are useful to all others in the community and the community guests. Thank you once again!
very nice.
but i am still confused why you define delegate DelegateFoundNumber outside the class.
DelegateFoundNumber
also please will you explain that when we invoke the event NumberFound(c); how it calls the delegate automatically.
NumberFound(c); how it calls the delegate automatically.
is this line MyNumb.NumberFound += new DelegateFoundNumber(myEvtCls.NeededNumberFound);
MyNumb.NumberFound +=
new
DelegateFoundNumber(myEvtCls.NeededNumberFound);
is reponsible for this behaviour.
ASK LIKE AN EDIOT UNDERSTAND LIKE A GENIOUS.
Hey Vinzy...
Thanks for your comment :).
this is the best article regarding delegates and events no doubt..after reading this i got the idea abt how delegate and events related to eacth other ..fantastic article..
Thank you for the comment and your questions @Zain Ali.
#1) The DelegateFoundNumber is defined outside the classes in order to be accessible from all other classes. Since I've defined the event (public event DelegateFoundNumber NumberFound;) inside the Numbers class and once this event happens, the delegate is invoked.
public
event
DelegateFoundNumber NumberFound;)
#2) You are partialy right since with MyNumb.NumberFound += new DelegateFoundNumber(myEvtCls.NeededNumberFound); we asign the method to be executed once the delegate is invoked and the delegate is invoked once the NumberFound event happens. So, NumberFound is an event that is fired once the condition inside the FindNumber() method from Numbers class are satisfied. The parameter that is passed to the NumberFound event is the parameter delegated by the delegate ;).
Hope this clears up your doubts.
If you have any more questions or doubts, please write back or you can open thread in the forum so that everyone can benefit from the chat :).
Thank you,Hajan
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18