Skip to content

Delegates and Events

Delegates and events provide a way to implement callbacks and event-driven programming in C#. They enable loose coupling between components and support the observer pattern.

Delegates

Delegates are type-safe function pointers that can hold references to methods. They enable method callbacks and support both single and multicast scenarios.

csharp
// Delegate declaration
public delegate void MessageDelegate(string message);

// Using delegates
public class Messenger
{
    public void SendMessage(string message)
    {
        Console.WriteLine(message);
    }
}

MessageDelegate delegate = new MessageDelegate(messenger.SendMessage);
delegate("Hello!");

Events

Events provide a way for objects to notify other objects when something of interest occurs. They implement the publisher-subscriber pattern and help maintain loose coupling.

csharp
public class Publisher
{
    // Event declaration
    public event EventHandler<EventArgs> OnDataReceived;

    protected virtual void RaiseEvent()
    {
        OnDataReceived?.Invoke(this, EventArgs.Empty);
    }
}

// Subscribing to events
publisher.OnDataReceived += (sender, e) => Console.WriteLine("Data received!");