An event can have many handlers. With the event handler syntax, we create a notification system. Events are used in many .NET programs (including Windows Forms).
We attach additional methods without changing other parts of the code. This makes programs easier to maintain. It makes code clearer.
We use the event keyword. It creates an original event. The .NET Framework has many existing events: these are covered elsewhere.
EventHandler
type. The event keyword is used to create an instance of an event.static
modifier on the event. We can access the static
event from a static
method (Main
).using System; public delegate void EventHandler(); class Program { public static event EventHandler _show; static void Main() { // Part 1: add event handlers to Show event. _show += new EventHandler(Dog); _show += new EventHandler(Cat); _show += new EventHandler(Mouse); _show += new EventHandler(Mouse); // Part 2: invoke the event. _show.Invoke(); } static void Cat() { Console.WriteLine("Cat"); } static void Dog() { Console.WriteLine("Dog"); } static void Mouse() { Console.WriteLine("Mouse"); } }Dog Cat Mouse Mouse
GetInvocationList
We can call methods on an event type. Here we use GetInvocationList
, which returns a Delegate object array. With reflection, we can print the names of the methods.
using System; public delegate void EventHandler(); class Program { public static event EventHandler _click; static void Main() { _click += new EventHandler(ClickItem); _click += new EventHandler(ClickItem); // Display all delegates. foreach (var item in _click.GetInvocationList()) { Console.WriteLine(item.Method.Name); } } static void ClickItem() { } }ClickItem ClickItem
Events let you add methods to be triggered upon an external event. You might add new event handlers dynamically for a specific action. Then, call Invoke to run them all.
Events are used in many objects in the .NET Framework. The Windows Forms framework uses events for many controls.
BackgroundWorker
type. We can monitor file system changes with FileSystemWatcher
.With events we separate something that happens from the behaviors we want to occur. Events are often used on the built-in types in the .NET Framework.