In this tutorial, we will delve into the process of handling events in C#. Event handling is a key aspect of creating interactive C# applications, and understanding this concept is crucial for every developer.
You will learn how to:
Prerequisites: Familiarity with C# basics and Object Oriented Programming principles.
In C#, an event is a way for a class to provide notifications to other classes when something of interest happens. The class that sends (or raises) the event is the publisher and the classes that receive (or handle) the event are the subscribers.
An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that make up a Windows Forms or WPF application will have events.
Delegates are a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type-safe, and secure.
Event handlers are methods in the subscriber class that will be executing the event. It must match the signature of the delegate.
// declaring the delegate
public delegate void MyEventHandler(string foo);
// declaring the event using the delegate
public event MyEventHandler MyEvent;
// method to raise the event
protected virtual void OnMyEvent(string foo)
{
MyEvent?.Invoke(foo);
}
In the code snippet above:
MyEventHandler
that takes a string as an argument.MyEvent
using this delegate.OnMyEvent
that invokes the MyEvent
. The ?.
operator is used to check if there is any subscriber to the event before invoking it.public class Subscriber
{
public void Subscribe(Publisher pub)
{
pub.MyEvent += RespondToEvent; // subscribing to the event
}
// event handler
private void RespondToEvent(string foo)
{
Console.WriteLine($"Event received: {foo}");
}
}
In the code snippet above:
Subscriber
class with a Subscribe
method. This method takes a Publisher
object and subscribes to its MyEvent
event by assigning an event handler RespondToEvent
.RespondToEvent
is defined to handle the event. It simply prints the message received from the event.In this tutorial, we've covered how to declare and define events in C#, how to subscribe to these events and how to respond when these events are raised. Events are a critical component of interactive applications in C#, allowing different parts of an application to communicate with each other in a loosely coupled way.
For further learning, look into more complex scenarios of event handling, such as handling multiple events, unsubscribing from events, and using built-in delegate types like Func
and Action
.
Create a Clock
class that raises an event Tick
every second.
Create a Reminder
class that subscribes to the Clock
and prints a reminder every minute.
Solutions
public class Clock
{
public delegate void SecondPassedHandler(object clock, EventArgs timeInfo);
public event SecondPassedHandler SecondPassed;
public void Run()
{
while (true)
{
Thread.Sleep(1000);
OnSecondPassed(EventArgs.Empty);
}
}
protected virtual void OnSecondPassed(EventArgs e)
{
SecondPassed?.Invoke(this, e);
}
}
public class Reminder
{
public void Subscribe(Clock clock)
{
clock.SecondPassed += OnSecondPassed;
}
private void OnSecondPassed(object clock, EventArgs timeInfo)
{
Console.WriteLine("Reminder: One second has passed");
}
}
In these examples, a Clock
class is created that raises an event every second. A Reminder
class is also created that subscribes to the Clock
's event and displays a reminder every second.