Modern GUIs rely on events generated by the user (or by the system) to know what action to take.
A delegate is a reference to a method of a particular signature and return type.
The keyword event
constrains a delegate’s usage to the event handling
semantics.
Instead of implementing delegates as static fields, you can implement them as properties, so that you do not need to instantiate them if they are never used.
You can combine delegates using the +=
operator.
An object can publish a series of events to which other classes can subscribe. The publishing class defines a delegate and an event based on that delegate. The subscribing class creates a method that matches the signature of the delegate, and registers that method with an instance of the delegate.
In .NET, all event handlers return void
, and take two parameters. The first
parameter is of type object and is the object that raises the event;
the second argument is an object of type EventArgs
or of a type derived from
EventArgs
, which may contain
useful information about the event.
Instead of passing a method name to a delegate, you can pass a block of code; this creates an anonymous method.