Start Coding

Topics

C# Events

Events are a powerful feature in C# that enable objects to notify other objects when something of interest occurs. They are an essential part of the C# Delegates mechanism and play a crucial role in implementing the Observer pattern.

What are C# Events?

An event is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The class that sends (or raises) the event is called the publisher, and the classes that receive (or handle) the event are called subscribers.

Declaring and Raising Events

To declare an event in C#, you use the event keyword followed by a delegate type. Here's a simple example:


public class Button
{
    public event EventHandler Click;

    public void OnClick()
    {
        Click?.Invoke(this, EventArgs.Empty);
    }
}
    

In this example, we declare an event named Click of type EventHandler. The OnClick method is responsible for raising the event.

Subscribing to Events

To subscribe to an event, you use the += operator. Here's how you can subscribe to the Click event:


Button button = new Button();
button.Click += Button_Click;

void Button_Click(object sender, EventArgs e)
{
    Console.WriteLine("Button was clicked!");
}
    

Custom Event Arguments

Sometimes, you may want to pass additional information when raising an event. You can do this by creating a custom event arguments class that inherits from EventArgs:


public class TemperatureChangedEventArgs : EventArgs
{
    public double NewTemperature { get; }

    public TemperatureChangedEventArgs(double newTemperature)
    {
        NewTemperature = newTemperature;
    }
}

public class Thermostat
{
    public event EventHandler<TemperatureChangedEventArgs> TemperatureChanged;

    private double _temperature;

    public double Temperature
    {
        get => _temperature;
        set
        {
            if (_temperature != value)
            {
                _temperature = value;
                OnTemperatureChanged(value);
            }
        }
    }

    protected virtual void OnTemperatureChanged(double newTemperature)
    {
        TemperatureChanged?.Invoke(this, new TemperatureChangedEventArgs(newTemperature));
    }
}
    

Best Practices

  • Always check if the event is null before invoking it to avoid null reference exceptions.
  • Use the "EventHandler" pattern for consistency and compatibility with .NET conventions.
  • Consider making the method that raises the event protected and virtual to allow derived classes to override the event-raising behavior.
  • Use custom event arguments when you need to pass additional information with the event.
  • Unsubscribe from events when they are no longer needed to prevent memory leaks.

Conclusion

Events in C# provide a powerful mechanism for loose coupling between objects. They are widely used in GUI programming, asynchronous programming, and many other scenarios where objects need to communicate without being tightly coupled. By mastering events, you'll be able to create more flexible and maintainable C# applications.

For more advanced event handling, consider exploring C# Delegates and C# Lambda Expressions, which can be used in conjunction with events to create more concise and expressive code.