C# Events
An event is a delegate field that other code can only subscribe to. The owning class alone decides when the event fires.
One subscriber hears the event
Button declares the Clicked event. Main subscribes one handler and presses the button.
using System;
class Button
{
public event Action<string> Clicked;
public void Press()
{
if (Clicked != null)
{
Clicked("pressed");
}
}
}
class Program
{
static void OnClicked(string label)
{
Console.WriteLine("Heard: " + label);
}
static void Main(string[] args)
{
Button button = new Button();
button.Clicked += OnClicked;
button.Press();
}
}Two subscribers in order
Two handlers subscribe to the same event. They run in subscription order.
using System;
class Button
{
public event Action<string> Clicked;
public void Press()
{
if (Clicked != null)
{
Clicked("pressed");
}
}
}
class Program
{
static void Announce(string label)
{
Console.WriteLine("First: " + label);
}
static void Log(string label)
{
Console.WriteLine("Second: " + label);
}
static void Main(string[] args)
{
Button button = new Button();
button.Clicked += Announce;
button.Clicked += Log;
button.Press();
}
}Raising with no subscribers
No handler subscribes in this program. The null check lets Press finish without an error.
using System;
class Button
{
public event Action<string> Clicked;
public void Press()
{
if (Clicked != null)
{
Clicked("pressed");
}
}
}
class Program
{
static void Main(string[] args)
{
Button button = new Button();
button.Press();
Console.WriteLine("Finished safely");
}
}Example
using System;
class Button
{
public event Action<string> Clicked;
public void Press()
{
if (Clicked != null)
{
Clicked("pressed");
}
}
}
class Program
{
static void Save(string label)
{
Console.WriteLine("Saved: " + label);
}
static void Show(string label)
{
Console.WriteLine("Shown: " + label);
}
static void Main(string[] args)
{
Button button = new Button();
button.Clicked += Save;
button.Clicked += Show;
button.Press();
button.Press();
}
}Key points
- The event keyword declares an event on a class.
- Code outside the class adds handlers with +=.
- Only the owning class can raise the event.
- Handlers run in the order they were added.
- An event with no handlers holds null.
In this example, two handlers subscribe to the Clicked event. The first press runs Save and then Show. The second press runs both handlers again in the same order.
Note
The null check makes raising an empty event safe.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does Press check Clicked for null first?