Letβs go through events in C# β a key concept for communication between objects.
π 1. What is an Event?
-
An event is a way for a class (the publisher) to notify other classes (subscribers) that something happened.
-
Events are based on Delegates, which define the signature of the method that handles the event.
-
Think of it as a βsignalβ that something occurred, and any interested object can react to it.
π 2. Basic Anatomy of an Event
-
Delegate β defines the method signature for event handlers
-
Event β defines the notification mechanism
-
Subscriber β a method that runs when the event is raised
Example: Simple Event
using System;
public class Alarm
{
// Step 1: Define delegate
public delegate void AlarmEventHandler(string message);
// Step 2: Define event
public event AlarmEventHandler AlarmRaised;
public void TriggerAlarm()
{
// Step 3: Raise the event
AlarmRaised?.Invoke("Alarm triggered!");
}
}
public class Program
{
static void Main()
{
Alarm alarm = new Alarm();
// Step 4: Subscribe to the event
alarm.AlarmRaised += HandleAlarm;
alarm.TriggerAlarm();
}
static void HandleAlarm(string msg)
{
Console.WriteLine($"Event received: {msg}");
}
}
Output:
Event received: Alarm triggered!
-
AlarmRaised?.Invoke(...)
β raises the event (safely checking for subscribers) -
alarm.AlarmRaised += HandleAlarm
β subscribes a method to the event
π 3. Key Points
Concept | Explanation |
---|---|
Delegate | Defines the signature of the event handler |
Event | Publisher sends notifications |
Subscriber | Object/method that reacts to the event |
Raising event | Uses Invoke() (or shorthand ?.Invoke ) to notify subscribers |
Syntax sugar | Can use EventHandler delegate for standard events: public event EventHandler MyEvent; |
π 4. EventHandler Shortcut
- Standardized delegate in .NET:
public event EventHandler SomethingHappened;
protected virtual void OnSomethingHappened()
{
SomethingHappened?.Invoke(this, EventArgs.Empty);
}
-
sender
β the object that raised the event -
EventArgs
β additional event information (can use a derived class for custom data)
π 5. Analogy
-
Publisher β alarm clock
-
Event β alarm bell ringing
-
Subscriber β person who hears the bell and reacts
β Tip:
-
Events in C# decouple classes β the publisher doesnβt need to know about subscribers.
-
Common in UI programming, async notifications, or reactive programming.