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:
Syntax
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
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
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
- Raising an event without checking for subscribers, so a null event throws; use
Event?.Invoke(...). - Trying to raise an event from outside the class that declares it, which is a compile error.
- 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: