← Back to C# Course | Chapter 12: Delegates & Events | Lesson 5 of 6

Events

In this page:

  1. Events

Events

An event is a delegate-based member that follows the publish/subscribe pattern — a class raises the event, and any number of external handlers can subscribe to react to it, without the publisher knowing who they are. Subscribers attach with += and the class raises the event internally by invoking it like a delegate. Events are how UI frameworks and many libraries notify code about state changes.

Note: An event can only be raised from inside its declaring class, even though outside code can subscribe to it.

Example: Events

markup
using System;

class Button
{
    public event Action Clicked;

    public void Click()
    {
        Console.WriteLine("Button clicked!");
        Clicked?.Invoke();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Button button = new Button();
        button.Clicked += () => Console.WriteLine("Handler: something happened");

        button.Click();
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.