Thursday, 26 August 2010

Events vs Delegates in C#

Today, somebody asked me to explain the difference between an event and a delegate in C#. Despite using the language for a long time now, I was quite taken back by the fact that couldn't describe the exact difference. The only thing I knew was that one need to define a delegate to declare an event.

A bit of searching took me to this very well explained post on the subject http://blog.monstuff.com/archives/000040.html

To sum it all up, an Event is actually a modifier on delegate i.e. makes it more restrictive. The main differences are

1) Event can be used in an interface definition while a delegate cannot be used.

2) Event can only be invoked from the class that declares it, while delegates can be invoked from child classes and clients.

3) Event comes with it's pair of accessors i.e Add and Remove. An event is always assigned and unassigned with a += and -= operator.

4) Event has a restrictive signature and must always be of the form Event (object source, EventArgs args)

Well, you learn something new everyday...

5 comments:

मुसाफ़िर said...

Hi Hamid,

I was going through one of your old posts on accessing the certificate store of a remote machine. When I tried to use the same code, it throws an error that can't connect to the remote machine, even though both the machines are in the same domain. Could you please help me out? this is a bit urgent.

Thanks in advance,
Mohit

Hamid said...

Hi Mohit,

It works for us on remote machines. What is the error that you are getting?

मुसाफ़िर said...

Hi Hamid,

Thanks for replying. For me, it is just not able to connect to the remote machine and comes back with the pointer 0 for the handle of the store. I tried it on multiple machines but of no help. Could you please help? I've used the exact code from your blog. If it is possible for you to give me your mail Id, that would be great. I can send in more details.

Mohit

Pavithra M said...



Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training in chennai velachery | dot net training institute in velachery

Mithun Mithun said...

It is really a great work and the way in which u r sharing the knowledge is excellent.
Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.. dot net training and placement in chennai | best dot net training in chennai