Why events with custom accessories cannot be triggered directly by default?

If I write something like the code below,

class MainClass { static EventHandler _myEvent= delegate{}; static event EventHandler MyEvent { add{_myEvent += value;} remove{_myEvent -= value;} } public static void Main (string[] args) { MyEvent(null,EventArgs.Empty); } } 

the compiler will complain: Error CS0079: MainClass.MyEvent event MainClass.MyEvent' can only appear on the left hand side of + =' or `- = '.

Why is something so strange as it even exists? If I cannot fire the event directly, why should I use such a thing in the first place? Is this a mistake (I use mono) or an intentional subtle design? Can someone teach me the rationale for this? Thanks in advance.

+6
source share
2 answers

You can only access the event in the declaring class. Behind the scenes, .NET creates private instance variables to hold the delegate.

The compiler actually creates a public event and a private field. You can access the field directly from one class or nested classes. From external classes you will be allowed to subscribe / unsubscribe.

Great information from Jon Skeet is available here on why this is and how it works.

+2
source

You need to call the manually processed delegate to raise the event: replace MyEvent(null, EventArgs.Empty) with _myEvent(null, EventArgs.Empty) . If you think about this, custom add / remove can store delegates anywhere, so you cannot extract and call them the way you wrote it ...

+2
source

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


All Articles