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...

6 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

Unknown said...

Great post! This is very useful for me and gain more information, Thanks for sharing with us.
Web Designing Training in Chennai

rmouniak said...

This blog gives very important info about.Net Thanks for sharing
.Net Online Training Hyderabad

Hallebose said...

Thanks for explaining these differences.