Event. 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.
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
A discussion. 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.
Tip Events can reduce the number of code changes needed. We can just add events, and not worry about calling locations.
Thus The event handler notification system provides a way to isolate different parts of your program from excessive changes.
Uses, Windows Forms. Events are used in many objects in the .NET Framework. The Windows Forms framework uses events for many controls.
Tip These events allow you to instantly act upon button clicks and key presses.
Note With threading, we use events on the BackgroundWorker type. We can monitor file system changes with FileSystemWatcher.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 21, 2023 (simplify).