event keyword
Context: The event keyword restricts how a delegate field can be used. Only the declaring class can invoke the event; outside code can only add or remove handlers.
Declaration
Section titled “Declaration”public class Publisher{ // Declare an event based on a delegate type public event EventHandler SomethingHappened;}Behind the scenes
Section titled “Behind the scenes”The compiler creates a private delegate field and adds add and remove accessors.
// Rough equivalentprivate EventHandler _somethingHappened;public event EventHandler SomethingHappened{ add { _somethingHappened += value; } remove { _somethingHappened -= value; }}Custom event accessors
Section titled “Custom event accessors”You can provide your own add/remove logic.
private EventHandler _handlers;public event EventHandler MyEvent{ add { _handlers += value; Console.WriteLine("Added"); } remove { _handlers -= value; Console.WriteLine("Removed"); }}Real-world usage example
Section titled “Real-world usage example”Property change notification: In MVVM frameworks, the PropertyChanged event is declared with the event keyword, allowing the view to subscribe.
Example: INotifyPropertyChanged uses an event PropertyChanged.