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

  1. Delegate β†’ defines the method signature for event handlers

  2. Event β†’ defines the notification mechanism

  3. 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

ConceptExplanation
DelegateDefines the signature of the event handler
EventPublisher sends notifications
SubscriberObject/method that reacts to the event
Raising eventUses Invoke() (or shorthand ?.Invoke) to notify subscribers
Syntax sugarCan 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.