Skip to content

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.

public class Publisher
{
// Declare an event based on a delegate type
public event EventHandler SomethingHappened;
}

The compiler creates a private delegate field and adds add and remove accessors.

// Rough equivalent
private EventHandler _somethingHappened;
public event EventHandler SomethingHappened
{
add { _somethingHappened += value; }
remove { _somethingHappened -= value; }
}

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"); }
}

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.