Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What so special about events when they are just delegates in C#?

Tags:

c#

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.

like image 573
Embedd_0913 Avatar asked May 18 '11 07:05

Embedd_0913


3 Answers

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.

like image 115
Gabe Avatar answered Oct 23 '22 21:10

Gabe


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.

like image 2
fearofawhackplanet Avatar answered Oct 23 '22 20:10

fearofawhackplanet


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.

like image 2
Brian Rasmussen Avatar answered Oct 23 '22 21:10

Brian Rasmussen