Event (C#)

An event is a notification a class sends out when something happens, so other code can react to it. It is built on delegates and is central to the publish–subscribe pattern.

C#

A class declares an event, other code 'subscribes' by attaching a handler method with +=, and when the class 'raises' the event every subscriber's method runs.

Events are everywhere in UI and game code — for example, reacting when a button is clicked or a timer ticks. The event keyword protects the delegate so only the owning class can raise it.

Syntax

public event Action OnSomething;

Examples

C#

class Button
{
    public event Action? Clicked;
    public void Click() => Clicked?.Invoke();
}

var b = new Button();
b.Clicked += () => Console.WriteLine("clicked!");
b.Click();

Output:

clicked!

Learn it in a lesson

See also

Back to the Dictionary