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.
instance.myEvent.Invoke();instead ofinstance.InvokeEvent();- Igor