Skip to content
C#

Delegates and Events

Define delegate types and publish events with safe subscription.

By EZ4Code Team
delegateevent

Code

using System;

public delegate void Notify(string message);

public class Button
{
    // Event restricts external invocation
    public event Notify? Clicked;

    public void Click()
    {
        Console.WriteLine("Button.Click raising event");
        Clicked?.Invoke("clicked at " + DateTime.Now.ToShortTimeString());
    }
}

class Program
{
    static void Main()
    {
        var btn = new Button();

        // Subscribe with named methods
        btn.Clicked += OnClickLog;
        // Subscribe with lambda
        btn.Clicked += msg => Console.WriteLine($"[lambda] {msg}");

        btn.Click();
        btn.Clicked -= OnClickLog;   // unsubscribe
        btn.Click();
    }

    static void OnClickLog(string message) =>
        Console.WriteLine($"[logger] {message}");
}

Explanation

A delegate is a type-safe function pointer; an event is a restricted delegate that only the owning class can invoke. Subscribers attach handlers with += and detach with -=, while the publisher raises the event with the null-conditional invoke pattern. This implements the observer pattern with built-in language support.

More C# Snippets