Hello, there is this example:

public delegate void EventDelegate(); public class MyClass { public event EventDelegate myEvent = null; public void InvokeEvent() { myEvent.Invoke(); } } class Program { // Методы обработчики события. static private void Handler1() { Console.WriteLine("Обработчик события 1"); } static private void Handler2() { Console.WriteLine("Обработчик события 2"); } static void Main() { MyClass instance = new MyClass(); // Присоединение обработчиков событий. (Подписка на событие) instance.myEvent += new EventDelegate(Handler1); instance.myEvent += Handler2; // Метод который вызывает событие. instance.InvokeEvent(); Console.WriteLine(new string('-', 20)); // Открепляем Handler2(). instance.myEvent -= new EventDelegate(Handler2); instance.InvokeEvent(); // Delay. Console.ReadKey(); } } 

Why is there an InvokeEvent method that calls the event myEvent?

Why bother recalling an event at all? Why not call it "directly" - as a method?

  • Why not call it "directly" - as a method? where exactly? - Grundy
  • @Grundy instance.myEvent.Invoke(); instead of instance.InvokeEvent(); - Igor

2 answers 2

Because you can’t call an event outside a class, you simply won’t compile it. Outside the class, you can only subscribe to the event or unsubscribe from it.

By the way, you incorrectly call event: in case there are no subscribers, your call will crash. Write like this:

 myEvent?.Invoke(); 
  • according to the mind, there should be a property of the delegate type of the event and a built-in subscription to the default handler, for example, empty, so as not to shamanize with the delegate's checks for emptiness and not be afraid of the user writing null to the delegate. - rdorn 8:01 pm
  • @rdorn: For my taste, this is too much user freedom. And if he wants to unsubscribe what he did not sign himself? It's like opening private fields. Let it be better with protection. - VladD
  • uh .. and how he will unsubscribe from what was not subscribed to? Okay, I'll put the demo of what I'm talking about in my answer, and discuss it there =) - rdorn
  • @rdorn: For example, assign a null property. - VladD
  • ready, maybe there are comments - rdorn

Events are intended to be called within the class in which they are defined, to inform subscribers that an event has occurred. Method instance.InvokeEvent(); needed to simulate the triggering of an event, no more. About why the call is being done this way, @VladD has already written.

About the code snippet:

 // Присоединение обработчиков событий. (Подписка на событие) instance.myEvent += new EventDelegate(Handler1); instance.myEvent += Handler2; // Метод который вызывает событие. instance.InvokeEvent(); 

This fragment demonstrates that if more than one handler subscribed to an event, all the signatories will be called when the event fires. In this case, the order of calling handlers is not guaranteed, although in most cases the call occurs as a subscription, it cannot be counted on even in a single-threaded program without asynchronous actions.

 // Открепляем Handler2(). instance.myEvent -= new EventDelegate(Handler2); instance.InvokeEvent(); 

Next, we are offered to unsubscribe from the event and call it again, thereby demonstrating that after the unsubscribe, the handler that we unsubscribed from the event will not be called. For this, the method of simulating an event is called a second time.

That's all for it. There is nothing more to say about a piece of code that is torn from the context If we consider this fragment as a demonstration of working with multycast delegates, then the example is not the best and practically does not demonstrate anything useful, except for an unsafe code that falls apart with any awkward movement.

And finally, how to still make the event safe for use by the user with arbitrary curvature of hands and logic (criticism is accepted)

 public class MyClass { private void _DefaultHandler() { } private event EventDelegate _myEvent += _DefaultHandler; public event EventDelegate MyEvent { add { _myEvent += value; } remove { _myEvent -= value; } } } 

The short syntax is as for the usual automatic properties SomeProperty{get; set;} SomeProperty{get; set;} for events is not yet available, although in theory it is possible to implement.

And a slightly more complicated example from MSDN documentation.