Language: EN

csharp-que-son-eventos

What are and how to use Events in C#

An event in C# is a mechanism that allows a class or an object to notify other classes or objects that something has occurred.

When an event occurs, associated methods are called allowing classes to react to the triggered actions.

Events are based on delegates, which are types that encapsulate references to methods. However, events have small differences compared to delegates. One of them is that only the class that has the event can invoke it.

Event Syntax

To define an event, we first need to define a delegate type that specifies the signature of the method we want to respond to the event. We call this function handler.

On the other hand, we need to declare the event itself. This uses the delegate type we defined earlier, preceding it with the reserved word event.

It seems a bit complicated and rigid, but it makes sense 😉. Later we will see that there is a simpler way to do it. But for now, it’s good to understand the basics.

Let’s look at an example,

// definition of the function that will handle the event
public delegate void MyEventHandler(string message);

public class Publisher
{
	// definition of the event
    public event MyEventHandler MyEvent;

    public void Notify(string message)
    {
        MyEvent?.Invoke(message);
    }
}

In this example,

  • MyEventHandler is the type of function that we want to “respond” to our event. In this case, these are methods that take a string as a parameter and do not return a value.
  • MyEvent is an event in itself. It is defined using the previous delegate, preceding the word event to indicate that it is an event.

Finally, when “whatever generates the event” has occurred, and we want to trigger it, we do

MyEvent?.Invoke(message)

How to Consume Events

Now we know how to define and fire Events. Now let’s see how other parts of the program can subscribe to these events to be informed that something has happened.

Subscribing to Events

To subscribe to an event, the += operator is used, adding an event handler method that matches the event’s delegate signature.

public static void PrintMessage(string message)
{
	Console.WriteLine("Event received: " + message);
}

// we create a publisher object
var publisher = new Publisher();

// we subscribe PrintMessage to the event
publisher.MyEvent += PrintMessage;

// we force the event to fire
publisher.Notify("Hello, event!");

// Output:
// Event received: Hello, event!

In this example, we subscribe the PrintMessage method in the Subscriber class to the MyEvent event of the Publisher.

In a real project, the Publisher object would be doing its thing. When it wants to report that it fires

Unsubscribing from Events

To unsubscribe from an event, the -= operator is used, removing the event handler method from the event.

publisher.MyEvent -= subscriber.HandleEvent;

Unsubscribing from events is important to avoid memory issues and dangling references, especially in long-running applications.

Using Generic Events

The normal syntax for creating Events in C# is a bit “verbose,” because we have to define a delegate with the signature of the method that will handle the event.

To simplify the syntax, the generic delegate EventHandler<TEventArgs> was introduced in version 2.0 of the .NET Framework.

This is the syntax you will typically use

This delegate provides a generic way to handle events, meaning it can handle any type of event arguments without having to define a custom delegate for each type of event.

public class Publisher
{
	// definition of the event
    public event EventHandler<string> MyEvent;

    public void Notify(string message)
    {
        MyEvent?.Invoke(this, message);
    }
}

EventHandler<TEventArgs> is a useful abstraction that encapsulates a method that takes two parameters:

  • The object that triggered the event (sender)
  • An object that contains data related to the event (TEventArgs). Usually, TEventArgs is a class that inherits from EventArgs and can contain additional information about the event.

Therefore, the functions that subscribe to the Event would look like this,

publisher.MyEvent += (s, e) => PrintMessage(e);

This is the most common form of EventHandler you will find in C#.

Practical Examples

Using Events with a Button

Although events are not exclusive to the User Interface, it is one of the main uses of events.

Let’s see how we could subscribe a function to the Click Event of a button in the User Interface.

Button button = new Button();
button.Click += (sender, args) => Console.WriteLine("Click event has occurred.");

Creating an Alarm

This example shows how to use Events outside the user interface scope. For example, creating an alarm that triggers an event when activated.

public class Alarm
{
    public event EventHandler AlarmActivated; // Defines an AlarmActivated event

    public void Activate()
    {
        AlarmActivated?.Invoke(this, EventArgs.Empty); // Fires the AlarmActivated event
    }
}

Alarm alarm = new Alarm();

// Subscribe to the AlarmActivated event
alarm.AlarmActivated += (sender, args) => Console.WriteLine("Alarm activated!");

// Activate the alarm
alarm.Activate();

Observer Pattern with Message Passing

This example implements a very simple observer pattern, where a sender sends messages to a receiver.

public class Sender
{
    public event EventHandler<string> MessageSent; // Defines a MessageSent event

    public void SendMessage(string message)
    {
        Console.WriteLine($"Message sent: {message}");
        MessageSent?.Invoke(this, message); // Fires the MessageSent event
    }
}

public class Receiver
{
    public Receiver(Sender sender)
    {
        // Subscribe to the sender's MessageSent event
        sender.MessageSent += (sender, message) => Console.WriteLine($"Message received: {message}");
    }
}

Sender sender = new Sender();
Receiver receiver = new Receiver(sender);

sender.SendMessage("Hello, receiver!");