C# - Events


An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises the event is called the event sender . The object that captures the event and responds to it is called the event receiver .

Events are declared using delegates.delegate object encapsulates a method so that it can be called anonymously. An event is a way for a class to allow clients to give it delegates to methods that should be called when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked.

Publishing and Subscribing

In C#, any object can publish a set of events to which other classes can subscribe . When the publishing class raises an event , all the subscribed classes are notified. With this mechanism, your object can say, "Here are things I can notify you about," and other classes might sign up, saying, "Yes, let me know when that happens." For example, a button might notify any number of interested observers when it is clicked. The button is called the publisher because the button publishes the Click event and the other classes are the subscribers because they subscribe to the Click event . Note that the publishing class does not know or care who (if anyone) subscribes ; it just raises the event. Who responds to that event , and how they respond, is not the concern of the publishing class .

The publisher and the subscribers are decoupled by the delegate .