An event is a mechanism for a class to be notified when something it is interested occurs. For example, continuing the long running search example above, an event could be the discovery of a match in that search. Events are also used in C# by user interface frameworks for modelling user interface events like button clicks. Events make use of delegate types to enable this. Events are a pattern that can increase the modularity of code by decoupling the event source from the event handler.
When one class notifies other classes that an event has occurred it is said to have raised an event
and is called the source of the event. Events are declared using the event keyword
and can be either instance or static fields of a class. You may declared accessors for events in a
similar way to get and set accessors for properties. However, the
accessors for events are add and remove. If you do not declared accessors
for an event the C# compiler will automatically generate them.
Here is a variation on the long running search example above using events. This time the event is when the search is finished. The class can be tested from the command line.
The key difference compared with the delegate example is that the callback did not
need to be passed in as a search method argument. This allows any number of event handlers to
be added and even removed later. For example, one event handler may alert the user that the search
is completed and another event handler may start the next search.
Adding the event handler is done in the program with the
+= operator. Removing an event handler can be done with the -= operator.
The add and remove event accessors are automatically generated by the
C# compiler in this example.
The output from this program is
To create an event that corresponds to the .NET Framework guidelines. These guidelines require that
the event take two parameters. The first parameter should be the source of the event. The second
parameter should derive from the System.EventArgs class. EventHandler is
useful for events that do not require any more information.
C# interfaces may also declare events. The implementing class should declare the same event with the
public access modifier. Even though the event is declared public outside code will only
be able to access it via the += and -= accessors.
There are no user comments.
Please send ideas and opinions by email at alexamies@gmail.com.