Understanding C# Events and Event Handling

Hello, C# developers! In this post, we’re going to explore events in C#. Events are a powerful programming feature that enables you to create a responsive, event-driven application architecture. They allow a class to provide notifications to clients of that class when a specific action or change occurs. Let’s dive in and understand how events work in C#!

What are Events?

Events are a special kind of delegate that enables a class or object to publish notifications to subscribing consumers. When an event occurs, an event handler can be called, allowing other parts of the application to respond to that event directly. This decouples the event producer from the event consumer, promoting better organization and maintainability in your code.

Defining an Event

In C#, you define an event using the event keyword, along with a delegate type. Here’s a simple example:

using System;

public delegate void ThresholdReachedEventHandler(object sender, EventArgs e);

public class TemperatureSensor
{
    public event ThresholdReachedEventHandler ThresholdReached;

    private int temperature;
    public int Temperature
    {
        get { return temperature; }
        set
        {
            temperature = value;
            if (temperature > 100)
            {
                OnThresholdReached(EventArgs.Empty);
            }
        }
    }

    protected virtual void OnThresholdReached(EventArgs e)
    {
        ThresholdReached?.Invoke(this, e);
    }
}

In this example, we have created a TemperatureSensor class that defines an event called ThresholdReached. When the Temperature property is set to a value greater than 100, the event is invoked, triggering any subscribed event handlers.

Subscribing to an Event

To respond to an event, you need to create an event handler method and subscribe it to the event. Here’s how you might use the TemperatureSensor class:

public class Program
{
    public static void Main()
    {
        TemperatureSensor sensor = new TemperatureSensor();
        sensor.ThresholdReached += Sensor_ThresholdReached;

        sensor.Temperature = 101; // This will trigger the event
    }

    private static void Sensor_ThresholdReached(object sender, EventArgs e)
    {
        Console.WriteLine("Threshold reached! Temperature is too high.");
    }
}

In this example, we created an instance of TemperatureSensor and subscribed to its ThresholdReached event with the Sensor_ThresholdReached method. When the temperature exceeds the threshold, our method gets called, printing a message to the console.

Event Arguments

To provide more information about the event when it is raised, you can create a custom event argument class that derives from EventArgs. Here’s how:

public class TemperatureEventArgs : EventArgs
{
    public int Temperature { get; }
    
    public TemperatureEventArgs(int temperature)
    {
        Temperature = temperature;
    }
}

public class TemperatureSensor
{
    public event EventHandler<TemperatureEventArgs> ThresholdReached;

    private int temperature;
    public int Temperature
    {
        get { return temperature; }
        set
        {
            temperature = value;
            if (temperature > 100)
            {
                OnThresholdReached(new TemperatureEventArgs(temperature));
            }
        }
    }

    protected virtual void OnThresholdReached(TemperatureEventArgs e)
    {
        ThresholdReached?.Invoke(this, e);
    }
}

Now, when the event is triggered, it provides a TemperatureEventArgs instance that contains the current temperature value.

Unsubscribing from Events

It’s important to unsubscribe from events when they are no longer needed to prevent memory leaks. You can unsubscribe using the -= operator:

public class Program
{
    public static void Main()
    {
        TemperatureSensor sensor = new TemperatureSensor();
        sensor.ThresholdReached += Sensor_ThresholdReached;

        sensor.Temperature = 101; // This will trigger the event

        // Unsubscribe from the event
        sensor.ThresholdReached -= Sensor_ThresholdReached;
    }

    private static void Sensor_ThresholdReached(object sender, TemperatureEventArgs e)
    {
        Console.WriteLine($"Threshold reached! Temperature: {e.Temperature}");
    }
}

In this program, we first subscribe to the event, then later unsubscribe from the event after use.

Conclusion

Events in C# provide a robust way to implement the observer pattern, allowing you to decouple components and create responsive applications. By understanding how to define, subscribe to, and raise events, you can enhance the interactivity and modularity of your applications.

To learn more about ITER Academy, visit our website. Visit Here

Scroll to Top