Events in C# Language
In the world of C# programming, events play a crucial role in building responsive and interactive applicatio
ns. Events are a fundamental concept that enables communication and interaction between objects or components within your code. In this post, we’ll explore what events are, how they work, and provide a practical example to illustrate their usage.Events in C# are a way to notify one or more objects when something interesting or important happens in your application. They provide a mechanism for communication between objects, often following a publisher-subscriber model. The object that generates the event is called the “publisher,” while the objects that respond to the event are the “subscribers” or “event handlers.”
Here’s a basic overview of how events work:
- Define an Event: You declare an event using the
event
keyword. This event is tied to a delegate type that defines the signature of the method that will handle the event. - Publish an Event: When a specific action or condition occurs, you raise the event, notifying any subscribed objects.
- Subscribe to an Event: Other objects in your code can subscribe to the event by providing a method that matches the delegate’s signature.
- Handle the Event: When the event is raised, the subscribed methods (event handlers) are executed.
Practical Example
Let’s illustrate events with a practical example. Suppose you are building a temperature monitoring system, and you want to alert the user when the temperature exceeds a certain threshold.
using System;
class TemperatureSensor
{
public event Action<int> TemperatureThresholdExceeded;
private int currentTemperature;
public TemperatureSensor()
{
currentTemperature = 0;
}
public void IncreaseTemperature(int amount)
{
currentTemperature += amount;
// Check if temperature exceeds the threshold (e.g., 100 degrees)
if (currentTemperature > 100)
{
OnTemperatureThresholdExceeded(currentTemperature);
}
}
protected virtual void OnTemperatureThresholdExceeded(int temperature)
{
// Check if there are any subscribers and invoke the event
TemperatureThresholdExceeded?.Invoke(temperature);
}
}
class Program
{
static void Main()
{
TemperatureSensor sensor = new TemperatureSensor();
// Subscribe to the event
sensor.TemperatureThresholdExceeded += temperature =>
{
Console.WriteLine($"Temperature threshold exceeded: {temperature} degrees!");
};
// Simulate a temperature increase
sensor.IncreaseTemperature(95);
sensor.IncreaseTemperature(10); // This will trigger the event
}
}
In this example, we have a TemperatureSensor
class with an event TemperatureThresholdExceeded
. When the temperature exceeds 100 degrees, it raises the event. The Program
class subscribes to this event and provides a method that gets executed when the event is triggered.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.