I am learning about events in C#. I found out that they are just multicast delegates.
My confusion is that why do we have "event"
keyword while they are delegate, can't we do
the same as we use delegates.
Events are essentialy properties whose types are delegates. The intent of the event
keyword is to denote what are actually events that an object fires (i.e. callback functions), versus properties that simply hold a delegate. This distinction is important to GUI tools that need to show you what events an object can fire. Of course this could have been done with an annotation, but that wasn't the design that was chosen for C#.
In a recent interview, Anders Hejlsberg (the creator of C#) mentions that if he were designing it over again, he would probably not make events so special.
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).
see here for a nice explanation.
Events restricts how the list of delegates can be manipulated as you can only add and remove delegates via the +=
and -=
operators. Delegates on the other hand do not carry this restriction so given the defintions below.
public event DelegateType Events;
public DelegateType Delegates;
You can do the following
instance.Delegates = null; // clear the list of delegates
but the compiler will prevent you from doing
instance.Events = null; // doesn't compile
When compiled the Events
field is actually private
despite its declaration as public
and the compiler simply adds add/remove methods for manipulating the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With