Meta Description:
Learn how to master events in C# with a step-by-step guide. This article explains the publish-subscribe pattern using a simple temperature monitoring system, complete with examples and assignments to help you practice your skills at various difficulty levels.
Events in C# are a fundamental feature that allows different parts of your application to communicate without being tightly coupled. Events follow the publish-subscribe pattern, where one object (the publisher) notifies others (the subscribers) when something significant happens. In this article, we’ll break down the concept of events in C# using a simple temperature monitoring system. This example is easy to understand and applicable in real-world scenarios. We’ll also provide assignments at different difficulty levels to help you practice your knowledge.
1. What are Events in C#?
Events are based on delegates in C#. They allow objects to send notifications when something happens, like a button click or a temperature rise. Events are ideal for scenarios where one object needs to notify other objects that something important has occurred.
In our temperature monitoring example, we’ll have a TemperatureSensor class that monitors room temperature. When the temperature exceeds a certain limit (e.g., 30°C), it raises an event to notify any interested subscribers.
2. Temperature Monitoring System Example
Let’s walk through the example of building a temperature monitoring system. This system will trigger an alert when the room’s temperature exceeds 30°C. Here’s how we’ll do it:
Step 1: Define the Event
In the TemperatureSensor
class, we’ll define an event called TemperatureExceeded
. This event will be triggered when the temperature surpasses a predefined threshold.
using System;
public class TemperatureSensor
{
// Define the event using the EventHandler delegate
public event EventHandler<TemperatureEventArgs> TemperatureExceeded;
private int _currentTemperature;
// Simulate temperature changes
public void CheckTemperature(int temperature)
{
_currentTemperature = temperature;
Console.WriteLine($"Current temperature: {_currentTemperature}°C");
if (_currentTemperature > 30)
{
OnTemperatureExceeded(_currentTemperature);
}
}
// Protected virtual method to raise the event
protected virtual void OnTemperatureExceeded(int temperature)
{
TemperatureExceeded?.Invoke(this, new TemperatureEventArgs(temperature));
}
}
// Custom event arguments to pass temperature data
public class TemperatureEventArgs : EventArgs
{
public int Temperature { get; }
public TemperatureEventArgs(int temperature)
{
Temperature = temperature;
}
}
Explanation:
- The
TemperatureSensor
class monitors the room’s temperature. - The
TemperatureExceeded
event is triggered when the temperature exceeds 30°C. - A custom
TemperatureEventArgs
class is used to pass the temperature value to the subscribers.
Step 2: Subscribe to the Event
Next, we’ll create a subscriber that listens for the TemperatureExceeded
event. In this case, the subscriber will display an alert message when the temperature exceeds the threshold.
public class Program
{
public static void Main(string[] args)
{
TemperatureSensor sensor = new TemperatureSensor();
// Subscribe to the TemperatureExceeded event
sensor.TemperatureExceeded += Sensor_TemperatureExceeded;
// Simulate different temperature readings
sensor.CheckTemperature(25); // No alert
sensor.CheckTemperature(32); // Alert will be triggered
}
// Event handler that gets called when the temperature exceeds the threshold
private static void Sensor_TemperatureExceeded(object sender, TemperatureEventArgs e)
{
Console.WriteLine($"Alert! Temperature exceeded: {e.Temperature}°C");
}
}
Explanation:
- We create a
Program
class where we subscribe to theTemperatureExceeded
event. - The
Sensor_TemperatureExceeded
method is the event handler that gets executed when the temperature exceeds 30°C. - The system prints an alert message with the current temperature.
3. Breaking Down How Events Work
In this example, the TemperatureSensor class acts as the publisher, raising the TemperatureExceeded
event when the temperature goes above 30°C. The subscriber is the Program
class, which listens for this event and reacts by printing an alert.
Publisher: TemperatureSensor
- This class is responsible for detecting changes in the temperature and raising an event when necessary.
Subscriber: Program
- The subscriber class subscribes to the event and handles it using an event handler method. In this case, the handler simply displays an alert when the event is triggered.
4. Understanding Event Patterns in C#
Events are a key mechanism in C# for implementing the publish-subscribe pattern. They allow a class (the publisher) to notify other classes (subscribers) when something occurs. The subscribers can then react by handling the event, without needing direct knowledge of how the publisher works. This creates loose coupling between components.
Some best practices for working with events in C#:
-
Use EventHandler: Always use
EventHandler
orEventHandler<T>
to follow the C# conventions. -
Naming Conventions: Name events in the past tense, such as
TemperatureExceeded
orFileDownloaded
, to indicate that something has already happened. - Unsubscribing from Events: Always unsubscribe from events when they are no longer needed to avoid memory leaks.
5. Assignments to Practice Events in C#
To help you apply what you’ve learned, here are three assignments at different difficulty levels:
Easy Level:
Modify the TemperatureSensor
class to raise an event when the temperature drops below 10°C. Create a new event called TemperatureDropped
and subscribe to it.
Hint: Add a second event to the TemperatureSensor
class and raise it when the temperature is less than 10°C.
Medium Level:
Allow the TemperatureSensor
to notify multiple subscribers. For example, one subscriber could display an alert on the console, while another logs the alert to a file.
Hint: Add multiple event handlers for the TemperatureExceeded
event.
Difficult Level:
Extend the TemperatureSensor
class to monitor both temperature and humidity. Raise an event when the temperature exceeds 30°C or when the humidity exceeds 70%. Use a custom event argument class to pass both temperature and humidity data.
Hint: Modify TemperatureEventArgs
to include humidity, and add a new event for humidity monitoring.
Conclusion
Events in C# offer a powerful way to implement communication between objects using the publish-subscribe pattern. By following this guide, you’ve learned how to define, raise, and subscribe to events using a practical example. The assignments provided will help you deepen your understanding of how events work in real-world scenarios.
Keep practicing with events, as mastering them will allow you to create more dynamic, scalable, and loosely coupled systems in C#.
Top comments (0)