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

Events

An event is like a doorbell: when something happens, everyone who signed up to listen gets told. The sender does not need to know who is listening.

In this page:

  1. Events
Syntax
csharp
class Publisher
{
    public event Action EventName;

    public void Raise()
    {
        EventName?.Invoke();
    }
}

publisher.EventName += HandlerMethod;   // subscribe

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();
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Raising an event without checking for subscribers, so a null event throws; use Event?.Invoke(...).
  2. Trying to raise an event from outside the class that declares it, which is a compile error.
  3. Forgetting to unsubscribe with -=, which can keep objects alive and cause memory leaks.
🔒

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.