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