C# › Delegates, Events & Lambdas
What is an event, and how does it differ from a plain public delegate field?
IntermediateAnswer
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.