Events: publish/subscribe, event keyword
Publish/subscribe with events: declare event, add/remove handlers, pass data via EventArgs, and raise with the OnX pattern.
Events overview
Goal: Publish/subscribe with events.
- Declare an event on the publisher
- Subscribe with +=, unsubscribe with -=
- Raise safely in the publisher
- Pass data using EventArgs
Basic event usage
Expose an event and let listeners attach/detach. Only the publisher invokes it.
using System;
public class Button
{
public event EventHandler Click;
public void SimulateClick()
{
// Safe raise: copy then invoke if not null (C# 6-safe)
EventHandler h = Click;
if (h != null) h(this, EventArgs.Empty);
}
}
public class Program
{
static void OnClick(object sender, EventArgs e)
{
Console.WriteLine("Clicked!");
}
public static void Main(string[] args)
{
Button b = new Button();
b.Click += OnClick; // subscribe
b.SimulateClick(); // prints "Clicked!"
b.Click -= OnClick; // unsubscribe
b.SimulateClick(); // no output
}
}
All lessons in this course
- delegate, Action/Func, closures
- Events: publish/subscribe, event keyword
- Event patterns, pitfalls (memory leaks)