C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Events

C# Events

Events are built on delegates and implement the observer (publish-subscribe) pattern — one object notifies many others when something happens.

1 - Declaring and Raising an Event

public class Button
{
    // Declare the event using EventHandler (built-in delegate)
    public event EventHandler? Clicked;

    public void Click()
    {
        Console.WriteLine("Button clicked.");
        Clicked?.Invoke(this, EventArgs.Empty); // raise the event
    }
}

var btn = new Button();

// Subscribe to the event
btn.Clicked += (sender, e) => Console.WriteLine("Handler 1: reacting to click!");
btn.Clicked += (sender, e) => Console.WriteLine("Handler 2: logging the click.");

btn.Click();
// Button clicked.
// Handler 1: reacting to click!
// Handler 2: logging the click.

2 - Custom EventArgs

public class OrderEventArgs : EventArgs
{
    public int OrderId { get; }
    public decimal Total { get; }
    public OrderEventArgs(int id, decimal total) { OrderId = id; Total = total; }
}

public class OrderService
{
    public event EventHandler<OrderEventArgs>? OrderPlaced;

    public void PlaceOrder(int id, decimal total)
    {
        // process order...
        OrderPlaced?.Invoke(this, new OrderEventArgs(id, total));
    }
}

var svc = new OrderService();
svc.OrderPlaced += (s, e) =>
    Console.WriteLine($"Order #{e.OrderId} placed — Total: {e.Total:C}");

svc.PlaceOrder(42, 99.99m);
// Order #42 placed — Total: $99.99

Note: Always use the ?.Invoke() syntax to raise events — it is null-safe and thread-safe (reads the delegate reference once). Never use the two-step null-check + call pattern, which has a race condition in multi-threaded code.

-Tip-

C# {"id":45,"topic_id":3,"name":"C# Delegates and Events","slug":"c-delegates-and-events","image":null,"description":"<p>Understand delegates, lambda expressions, Func\/Action, and the event pattern in C#.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":14,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: