Events
In this page:
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
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();
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: