What is an event, and how does it differ from a plain public delegate field?
Short answer
An event wraps a delegate but RESTRICTS external code to only += (subscribe) and -= (unsubscribe) — external code can't directly invoke the event or overwrite its entire subscriber list with '=', which a plain public delegate field would allow, protecting the publishing class's…
Advertisement
AModel answer
An event wraps a delegate but RESTRICTS external code to only += (subscribe) and -= (unsubscribe) — external code can't directly invoke the event or overwrite its entire subscriber list with '=', which a plain public delegate field would allow, protecting the publishing class's control over when the event actually fires.
public class Button {
public event EventHandler? Clicked; // safe: outside code can only += or -=
public void SimulateClick() => Clicked?.Invoke(this, EventArgs.Empty);
}
var button = new Button();
button.Clicked += (sender, e) => Console.WriteLine("Clicked!");
// button.Clicked = null; // Error: can't do this from outside the classReal-world example
Implementing a UI button's Click event, or a domain model's OnOrderPlaced event that other parts of the system subscribe to.
Likely follow-ups
- Why is the null-conditional operator (?.Invoke) commonly used when raising an event?
Related topics