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.
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.
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.
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!");
}
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));
}
}
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.