Implementing Event Handling in C#

Tutorial 4 of 5

Implementing Event Handling in C

1. Introduction

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:

  • Define and declare events
  • Create subscribers
  • Respond to events

Prerequisites: Familiarity with C# basics and Object Oriented Programming principles.

2. Step-by-Step Guide

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.

Events

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

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

Event handlers are methods in the subscriber class that will be executing the event. It must match the signature of the delegate.

3. Code Examples

// 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:

  • We first declare a delegate MyEventHandler that takes a string as an argument.
  • We then declare an event MyEvent using this delegate.
  • Then we define a method OnMyEvent that invokes the MyEvent. The ?. operator is used to check if there is any subscriber to the event before invoking it.

Subscribing to an Event

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:

  • We define a Subscriber class with a Subscribe method. This method takes a Publisher object and subscribes to its MyEvent event by assigning an event handler RespondToEvent.
  • The RespondToEvent is defined to handle the event. It simply prints the message received from the event.

4. Summary

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.

5. Practice Exercises

  1. Create a Clock class that raises an event Tick every second.

  2. Create a Reminder class that subscribes to the Clock and prints a reminder every minute.

Solutions

  1. Clock Class
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);
    }
}
  1. Reminder Class
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.