C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The delegate keyword is used to specify the EventHandler type. The event keyword is used to create an instance of an event.
Static: We use the static modifier on the event. We can access the static event from a static method (Main).
StaticPart 1: The _show event has 4 method instances added to its invocation list with the plus "+=" operator.
Part 2: The Invoke method is called. This in turn causes each of the 4 method instances to be run. The strings are printed to the console.
ConsoleC# program that uses event
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");
}
}
Output
Dog
Cat
Mouse
Mouse
C# program that uses GetInvocationList
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()
{
}
}
Output
ClickItem
ClickItem
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.
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.
BackgroundWorkerFileSystemWatcherQuote: An event is a member that enables an object or class to provide notifications. Clients can attach executable code for events by supplying event handlers (The C# Programming Language).