Beginners guide to Event and EventHandler in C#
Events in C# plays a major role in a Windows Forms or a GUI based application. Event and EventHandler's are used to execute an action block based on some external events such as OnClick, OnMouseOver, OnTimerStopped and so on. Along with the in-built event, a user are allowed to create and consume any number of events depending on the requirement.
To create custom events, delegates are must. In order to keep this article simple and easy for beginners we are going to skip the part of creating delegates and consume the built-in EventHandler delegate. Using event with custom delegates will be explained as last part in this article.
Steps to create Event using EventHandler (A built-in delegate)
We can split the life-cycle of events into two categories. One the class or code which triggers the event and second the class which receives the events. For easy understanding, we are calling the class, which triggers the event as Sender class and the one, which receives as receiver class.
The steps explained below are with reference to example code shown in this article
Sender Class (Class that sends event updated to other classes)
1. Declare an event with a variable name of your choice by consuming EventHandler (Built-in delegate)
public event EventHandler TimeUpdate;
2. Check if the event is null and call Invoke function to trigger event to other classes.
if (TimeUpdate != null) TimeUpdate.Invoke(DateTime.Now.ToString(), null);
We are checking our event is null before invoking is to see if any other class is registered to receive our event update. Checking for null is a good practice to avoid any null pointer exception during run time.
Receiver Class (Class that listens/receives event update)
1. Register to the event update using += operator, and point to a function
timer.TimeUpdate += Timer_TimeUpdate;
2. Perform your required action inside the registered function.
Code example for Event and Eventhandler using C#
In the code explained, we have only one Console.WriteLine statement. Whenever the event is triggered, it will be received by the function Timer_TimeUpdate and will write the data to console.
using System; using System.Threading; //www.CraftedForEveryone.com namespace LearnEventHandling { class Program //Receiver Class { static void Main(string[] args) { Timer timer = new Timer(); timer.TimeUpdate += Timer_TimeUpdate; //Registering to event update timer.Processor(); } //Registered function //The signature of the function will match to that of EventHandler signature private static void Timer_TimeUpdate(object sender, EventArgs e) { //consuming the data received through event update Console.WriteLine(sender.ToString()); } } class Timer //Sender Class { public event EventHandler TimeUpdate; //Creating our custom event public void Processor() { while(1==1) { Thread.Sleep(1000); if (TimeUpdate != null) TimeUpdate.Invoke(DateTime.Now.ToString(), null); //Triggering the event } } } }