Events
Events are behaviors or happenings that occur when the program is running. Events are often used in visual programming like windows and web forms. Some examples of events are clicking a mouse, typing a text in a text box, changing the selected item in a list and many more. In console applications, we can manually trigger events. You must subscribe to an event which means adding event handlers or code blocks that will be executed when a particular event happens. Multiple event handlers can subscribe to an event. When an event triggers, all the event handlers will execute. The following example shows a simple usage of events.
using System;
namespace EventsDemo
{
public delegate void MessageHandler(string message);
public class Message
{
public event MessageHandler ShowMessage;
public void DisplayMessage(string message)
{
Console.WriteLine(message);
}
public void ExecuteEvent()
{
ShowMessage("Hello World!");
}
}
public class Program
{
public static void Main()
{
Message myMessage = new Message();
myMessage.ShowMessage += new MessageHandler(myMessage.DisplayMessage);
myMessage.ExecuteEvent();
}
}
}
Example 1 – Events Demo
Hello World!
An event handler is a method that matches the signature of a delegate. For example, we defined a delegate that has a void return type and one string parameter. This will be the signature of the event handler method. After defining the delegate, we created a class that contains an event. To define an event, the following syntax is used.
accessSpecifier event delegateType name;
The delegate type is the type of delegate to be used. The delegate is used to determine the signature of the event handler that can subscribe to it. We created an event handler DisplayMessage that has the same signature as the delegate. We also created another method that will trigger the event manually. Events cannot be triggered outside the class the contains it. Therefore, we will use this method to indirectly execute it. Inside our Main method, we created a new instance of the Message class. On the next line, an event handler subscribed to our event. Notice we used the += operator which means, we are adding the event handler to the list of event handlers for an event. We created a new instance of MessageHandler delegate and inside it, we passed the name of the event handler. We then call the ExecuteEvent method to trigger the event and show the message. You will see the usefulness of events when you work with windows forms or web forms in ASP.NET.