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

I will learn about events in C #. I found out that they are just multicast delegates.

My confusion is why we have the keyword "event" while they are delegated, can we do

same as we use delegates.

+6
source share
4 answers

Events are important properties whose types are delegates. The purpose of the event keyword is to denote what is actually the event that the object fires (i.e. callback functions), compared to the properties that the delegate just holds. This difference is important for GUI tools, which should show you what events the object may trigger. Of course, this could be done with annotation, but it was not the design that was chosen for C #.

In a recent interview , Anders Halesberg (creator of C #) mentions that if he develops it again, he probably won’t make the events so special.

+6
source

the event keyword is a modifier for the delegate, which allows it to be included in the interface, restricts its call from inside the class declaring it, it provides with a couple of custom Accessories (add and remove) and the delegate signature strength (when used within the framework of the .NET platform).

see here for a nice explanation.

+2
source

Events restrict access to the delegate list, since you can only add and remove delegates using the += and -= operators. Delegates, on the other hand, do not bear this restriction, so given the shortcomings 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 stop you from executing

 instance.Events = null; // doesn't compile 

When the Events field is compiled, it is actually private , despite its declaration as public , and the compiler simply adds add / remove methods to manage the list.

+2
source

The member declared with the event keyword is indeed MulticastDelegate . The only specialty is that although you are declaring a public event, you can only call an event / delegate from your class. This is because the compiler creates a private field that stores delegate and public methods for subscribing and unsubscribing to an event. If you used Delegate directly, someone from outside allowed you to call a delegate at any time.

So, the event is really just great delegate encapsulation.

+1
source

Source: https://habr.com/ru/post/888382/


All Articles