It might be the syntax of C# that provides us with shortcuts to write delegates and events that causes this confusion.
In short, a delegate is a class that contains a field that holds a reference to a method and then you can call the method with appropriate parameters. Whereas an event is a variable that you can define and specify one or more delegates to be added to it.
Let's go through these examples to simplify and illustrate the idea.
In the previous code, I create a delegate type and name it
In the execute method, I create an instance of the delegate (recall that a delegate is a class and I can create instances from it like any other class). The constructor of this
Another point that is worth mentioning is that I could have invoked the method without using the Invoke method. This is just a syntactical shortcut provided by C#. It would be like this:
Now let's change our code a little bit. (comment added to show added, removed and changed code)
What I did is just changing the parameters that
Now I will introduce an event and see how to use it. I will change the code a little bit. (comment added to show added, removed and changed code )
Here's what I did in the last code change.I declared an event of type
As you can see,
Instead of adding a delegate instance to the event the normal way, There's a syntax shortcut provided by C# that looks like this:
Notice that I no longer need to create delegate instances because the new syntax will implicitly create it.
Finally, let me introduce
As you can see,
Normally, you don't go through all of the previous steps. You only see the last portion of code. All I was trying to do is to show you how this last code came.
now I hope it became clear that delegates are just types that you can create instances from. All delegates inherit from the classMulticastDelegate which is used to invoke other methods according to what we define. Events are meant to hold one or more delegate instance and once you raise the event, it invokes all the methods attached with those delegate instance.
In short, a delegate is a class that contains a field that holds a reference to a method and then you can call the method with appropriate parameters. Whereas an event is a variable that you can define and specify one or more delegates to be added to it.
Let's go through these examples to simplify and illustrate the idea.
class Program { static void Main(string[] args) { DelegatesAndEvents obj = new DelegatesAndEvents(); obj.Execute(); } } public class DelegatesAndEvents { public delegate void MyDelegate(int val); internal void Execute() { MyDelegate d = new MyDelegate(this.MyMethod); int val = 15; d.Invoke(val); } void MyMethod(int val) { Console.WriteLine(val); Console.ReadLine(); } }
In the previous code, I create a delegate type and name it
MyDelegate
. This delegate type is designed to call methods that take one parameter of type integer. What actually happens behind the scenes is that the CLR creates a class called MyDelegate
and this class would have some fields and a method called Invoke. The invoke method takes one parameter of type integer.In the execute method, I create an instance of the delegate (recall that a delegate is a class and I can create instances from it like any other class). The constructor of this
MyDelegate
takes one parameter of type integer. However, what I actually pass to the constructor is the name of the method I want to invoke and it will implicitly understand that I'm passing a reference to the method.Another point that is worth mentioning is that I could have invoked the method without using the Invoke method. This is just a syntactical shortcut provided by C#. It would be like this:
d(val);
Now let's change our code a little bit. (comment added to show added, removed and changed code)
public class DelegatesAndEvents { public delegate void MyDelegate(object sender, EventArgs e); // Changed internal void Execute() { MyDelegate d = new MyDelegate(this.MyMethod); EventArgs e = new EventArgs(); // Added object sender = 15; // Added d(sender, e); // Changed } void MyMethod(object sender, EventArgs e) { Console.WriteLine(sender); Console.ReadLine(); } }
What I did is just changing the parameters that
MyDelegate
is designed to take. Instead of taking one parameter of type integer, it now takes 2 parameters of types object and EventArgs, respectively. There's no big deal so far.Now I will introduce an event and see how to use it. I will change the code a little bit. (comment added to show added, removed and changed code )
public class DelegatesAndEvents { public delegate void MyDelegate(object sender, EventArgs e); public event MyDelegate MyEvent; // Added internal void Execute() { MyDelegate d = new MyDelegate(this.MyMethod); object sender = 15; EventArgs e = new EventArgs(); MyEvent += new MyDelegate(d); // Added MyEvent(sender, e); // Added //d(sender, e); Removed } void MyMethod(object sender, EventArgs e) { Console.WriteLine(sender); Console.ReadLine(); } }
Here's what I did in the last code change.I declared an event of type
MyDelegate
. In other words, I created an event that can hold delegates of type MyDelegate
, so in the future I can use this event to invoke methods with the signature MyDelegate
defines (methods that take 2 parameters of type object and EventArgs). And then,instead of invoking MyMethod directly using the delegate, I use the newly created event MyEvent
to invoke the method.As you can see,
MyEvent
is just a holder of delegates. I can add delegates to this event by using += syntax and passing the delegate instance in the constructor. I can add more than one delegate instance to this event. Look at the following code. (comment added to show added, removed and changed code )public class DelegatesAndEvents { public delegate void MyDelegate(object sender, EventArgs e); public event MyDelegate MyEvent; internal void Execute() { MyDelegate d = new MyDelegate(this.MyMethod); object sender = 15; EventArgs e = new EventArgs(); MyDelegate d2 = new MyDelegate(this.MyMethod2); // Added MyEvent += new MyDelegate(d); MyEvent += new MyDelegate(d2); // Added MyEvent(sender, e); } void MyMethod(object sender, EventArgs e) { Console.WriteLine(sender); Console.ReadLine(); } // This method is added void MyMethod2(object sender, EventArgs e) { Console.WriteLine(sender); Console.ReadLine(); } }
Instead of adding a delegate instance to the event the normal way, There's a syntax shortcut provided by C# that looks like this:
MyEvent += MyMethod;So I can change my code to look like this: (comment added to show added, removed and changed code )
class DelegatesAndEvents { public delegate void MyDelegate(object sender, EventArgs e); public event MyDelegate MyEvent; internal void Execute() { //MyDelegate d = new MyDelegate(this.MyMethod); Removed object sender = 15; EventArgs e = new EventArgs(); //MyDelegate d2 = new MyDelegate(this.MyMethod2); Removed MyEvent += MyMethod; // Changed MyEvent += MyMethod2; // Changed MyEvent(sender, e); } void MyMethod(object sender, EventArgs e) { Console.WriteLine(sender); Console.ReadLine(); } void MyMethod2(object sender, EventArgs e) { Console.WriteLine(sender); Console.ReadLine(); } }
Notice that I no longer need to create delegate instances because the new syntax will implicitly create it.
Finally, let me introduce
EventHandler
, which is a delegate type itself. You can type EventHandler
in your code in Visual Studio and press F12 to discover this.namespace System { [Serializable] [ComVisible(true)] public delegate void EventHandler(object sender, EventArgs e); }
As you can see,
EventHandler
is a delegate type designed to invoke methods that take 2 parameters, object and EventArgs, exactly like MyDelegate
that I defined in the previous code. Therefore, I can replace MyDelegate
with EventHandlerand
everything will be the same. The final code will be like this:class DelegatesAndEvents { //public delegate void MyDelegate(object sender, EventArgs e); Removed public event EventHandler MyEvent; // Changed internal void Execute() { object sender = 15; EventArgs e = new EventArgs(); MyEvent += MyMethod; MyEvent += MyMethod; MyEvent(sender, e); } void MyMethod(object sender, EventArgs e) { Console.WriteLine(sender); Console.ReadLine(); } void MyMethod2(object sender, EventArgs e) { Console.WriteLine(sender); Console.ReadLine(); } }
Normally, you don't go through all of the previous steps. You only see the last portion of code. All I was trying to do is to show you how this last code came.
now I hope it became clear that delegates are just types that you can create instances from. All delegates inherit from the classMulticastDelegate which is used to invoke other methods according to what we define. Events are meant to hold one or more delegate instance and once you raise the event, it invokes all the methods attached with those delegate instance.
http://msdn.microsoft.com/en-us/library/17sde2xt.aspx
ReplyDeleteThanks Ibrahim for sharing this article. I'm trying to explain it my way. Hope you found it helpful.
ReplyDeleteGot it...
ReplyDeletethanks for such a good explanation
Maximum.. superb..
ReplyDeleteThanks Sanyam and Dumindra for your comments.
ReplyDeleteGood article keep writing more article
ReplyDeleteVery Good Explaination. Thankyou!
ReplyDeleteThanks Niyas and Jitendra. You're welcome
ReplyDeleteVvery helpful, indeed!
ReplyDeleteBut please change
MyDelegated = new
MyDelegate(this.MyMethod);
to
MyDelegate d = new
MyDelegate(this.MyMethod);
(more than once)
I've lost a few minutes trying to figure it out!
Thanks for your point Euphemistic. It is corrected now.
ReplyDeleteGreat Explanation !!!
ReplyDeleteBest explanation I could find so far - Well done!
ReplyDeleteThanks Ken
ReplyDeleteYour Explanation was superb..Keep it up
ReplyDeleteThanks for explaining that well... its really awesome...
ReplyDeleteYou're welcome Abuzer
ReplyDeleteNeat explains
ReplyDeletevery very simple and crisp explanation. Thanks
ReplyDeleteI totally understood the explanation, and it was very clear. but the question is that if both Delegates and events are used for the same purpose, that is, calling methods of similar signatures, then why these are 2 different things? why not only delegates, or only events? after all they both do the exactly same job. Please explain what is the difference. Thanks in advance.
ReplyDeleteAmir Shaharyar Siddiqui, "the event keyword is a modifier for a delegate declaration that allows it to be included in an interface, constraints it invocation from within the class that declares it, provides it with a pair of customizable accessors (add and remove) and forces the signature of the delegate (when used within the .NET framework".
ReplyDeleteYou can take a look here: http://blog.monstuff.com/archives/000040.html
Thanks, well explained!
ReplyDeleteReally Nice article.So crystal clear
ReplyDeletethis is very nice post on the topic Nice explanation Ali .... Thanks a lot to clear the difference.
ReplyDeleteIt is a Excellent article Sir. I have long time confusion over relationship between the event and the delegate this article cleared everything. Thank you very much for your contribution.
ReplyDeleteSuperb article...step by step explanation made delegate and event very easy for me .. thank u so much
ReplyDeleteFantastic - Since there are so many ways to implement delegates / events, this clears up where a particular example code may fall within the process just explained.
ReplyDeleteFantastic - Since there are so many ways to implement delegates / events, this clears up where a particular example code may fall within the process just explained.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteNice, which helps more useful and meaningful, as a fresher we can easily understand this criteria. Dot Net Training in Chennai| best Dot net training in chennai
ReplyDeleteTry this.....C# Interview Questions
ReplyDeleteLing
best answer on internet til now. Thanks buddy...
ReplyDeleteIt 's an amazing article and useful for developers
ReplyDeleteDot Net Online Training
Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.
ReplyDeleteangularjs Training in marathahalli
angularjs interview questions and answers
angularjs Training in bangalore
angularjs Training in bangalore
angularjs Training in chennai
automation anywhere online Training
Nice tips. Very innovative... Your post shows all your effort and great experience towards your work Your Information is Great if mastered very well.
ReplyDeleteJava training in Chennai | Java training institute in Chennai | Java course in Chennai
Java training in Bangalore | Java training institute in Bangalore | Java course in Bangalore
Java online training | Java Certification Online course-Gangboard
Java training in Pune
Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information.
ReplyDeleterpa training in chennai
rpa training in bangalore
rpa course in bangalore
best rpa training in bangalore
rpa online training
This information is really awesome thanks for sharing most valuable information.
ReplyDeleteRPA Automation Anywhere Training
RPA Automation Anywhere Online Training
This informative post is showing the importance of web applications, so get your applications fast from here.
ReplyDeleteDevops Training in Chennai | Devops Training Institute in Chennai
Its a wonderful post and very helpful, thanks for all this information. You are including better information regarding this topic in an effective way.Thank you so much
ReplyDeleteRPA Online Training
indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
ReplyDeleteSOFTWARE TRAINING IN CHENNAI
POWERBI TRAINING IN CHENNAI
CCNA TRAINING IN CHENNAI
ANDROID TRAINING IN CHENNAI
It's awesome blog! thanks for this wonderful information with us..
ReplyDeleteTOEFL Coaching in Chennai
Classes in Chennai
German Classes in Chennai
IELTS Coaching in Chennai
Spoken English Classes in Chennai
Japanese Classes in Chennai
spanish classes in chennai
TOEFL Coaching in OMR
TOEFL Coaching in Porur
TOEFL Coaching in Adyar
Really very nice blog information for this one and more technical skills are improving, I like that kind of post.
ReplyDeleteStart your journey with RPA Course and get hands-on Experience with 100% Placement assistance from Expert Trainers with 8+ Years of experience @eTechno Soft Solutions Located in BTM Layout Bangalore.
Great post! I really appreciate your good efforts and this is the best blog for this title. I waiting for your more posts.share relaed to this.
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
Nice! you are sharing such helpful and easy to understandable blog. i have no words for say i just say thanks because it is helpful for me.
ReplyDeleteDot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery
Nice information thank you,if you want more information
ReplyDeleteOracle Training in Chennai | Certification | Online Training Course | Oracle Training in Bangalore | Certification | Online Training Course | Oracle Training in Hyderabad | Certification | Online Training Course | Oracle Training in Online | Oracle Certification Online Training Course | Hadoop Training in Chennai | Certification | Big Data Online Training Course
Very interesting blog Thank you for sharing such a nice and interesting blog and really very helpful article.I have recently visited your blog profile. I am totally impressed by your blogging skills and knowledgeData Science Training In Chennai
ReplyDeleteData Science Online Training In Chennai
Data Science Training In Bangalore
Data Science Training In Hyderabad
Data Science Training In Coimbatore
Data Science Training
Data Science Online Training
betmatik
ReplyDeletekralbet
betpark
mobil ödeme bahis
tipobet
slot siteleri
kibris bahis siteleri
poker siteleri
bonus veren siteler
Z37K