An event declaration is simply a special kind of property that is used to display a delegate. Instead of receiving and installing accessors, it creates and removes them. They usually execute automatically, but if you want to add custom behavior:
private MyEventHandler handler; public event MyEventHandler MyEvent { add { handler += value; Trace.WriteLine("MyEvent handler attached."); } remove { handler -= value; Trace.WriteLine("MyEvent handler removed."); } }
It does two things. First, since events are properties, they can be included in interfaces. Secondly, since MyEvent does not return a value, the delegate is fully encapsulated, and only the object calling it can call it. Other ways to display delegates make it possible for a delegate to be called by anyone.
Besides this bit of special language support, another significant difference between events and delegates is more a convention than a language or structure: events are expected to follow certain patterns , for example, make sure the delegate on which the event is based follows the pattern set by the EventHandler delegate .
As a rule, events are preferable whenever semantics refers to an object that notifies anyone who is interested in changing its stage. Delegation is preferable in situations where you want others to be able to define behavior by providing their own procedure, such as delegate parameters, that are executed by many extension methods in IEnumerable that are used in LINQ.
source share