Let’s go through delegates and events again in C# — fundamental concepts for type-safe callbacks (Function Delegates) and Events-driven programming.


📌 1. Delegates

A delegate is a type that represents a method signature.

  • Allows you to store a reference to a method and call it later

  • Provides type safety for methods used as callbacks

  • Similar to function pointers in C/C++, but safe and managed

Basic Syntax

public delegate void MyDelegate(string message);
  • MyDelegate can reference any method that takes a string and returns void

📌 2. Using Delegates

public class Program
{
    public static void PrintMessage(string msg)
    {
        Console.WriteLine(msg);
    }
 
    public static void Main()
    {
        MyDelegate del = PrintMessage;  // Assign method to delegate
        del("Hello, Delegates!");       // Invoke delegate
    }
}
  • del stores a reference to PrintMessage

  • Calling del() invokes the method


📌 3. Multicast Delegates

  • Delegates can point to multiple methods

  • Use += to add methods, -= to remove

public static void Method1(string msg) => Console.WriteLine("Method1: " + msg);
public static void Method2(string msg) => Console.WriteLine("Method2: " + msg);
 
MyDelegate del = Method1;
del += Method2;
 
del("Hello"); 
// Output:
// Method1: Hello
// Method2: Hello

📌 4. Events

  • An event is a special delegate that allows publish-subscribe behavior

  • Typically used to notify multiple subscribers about something happening

  • Declared using the event keyword

Syntax

public class Publisher
{
    public delegate void Notify(string message); // Delegate
    public event Notify OnNotify;               // Event
 
    public void RaiseEvent(string msg)
    {
        OnNotify?.Invoke(msg);  // Invoke event safely
    }
}

📌 5. Subscribing to Events

public class Subscriber
{
    public void HandleNotification(string message)
    {
        Console.WriteLine("Received: " + message);
    }
}
 
Publisher pub = new Publisher();
Subscriber sub = new Subscriber();
 
pub.OnNotify += sub.HandleNotification; // Subscribe
pub.RaiseEvent("Event triggered!");     // Output: Received: Event triggered!
  • Multiple subscribers can listen to the same event

  • Use -= to unsubscribe


📌 6. Key Differences: Delegate vs Event

FeatureDelegateEvent
TypeHolds reference to method(s)Wrapper around delegate for notifications
AccessibilityCan be invoked directlyCan only be invoked by declaring class
Use CaseCallbacks, method referencesPublisher-subscriber pattern
Syntaxdelegate void MyDel()public event MyDel MyEvent;

📌 7. Best Practices

  1. Use events for notifications to multiple subscribers

  2. Use delegates for single callbacks or passing methods

  3. Use ?.Invoke() to safely invoke events

  4. Follow naming conventions: delegates end with Handler, events end with Event


Example: Combining Delegate and Event

public delegate void AlarmHandler(string message);
 
public class Alarm
{
    public event AlarmHandler OnAlarm;
 
    public void Trigger(string message)
    {
        OnAlarm?.Invoke(message);
    }
}
 
public class Program
{
    public static void Main()
    {
        Alarm alarm = new Alarm();
        alarm.OnAlarm += msg => Console.WriteLine("Alarm received: " + msg);
        alarm.Trigger("Wake up!"); // Alarm received: Wake up!
    }
}