Events

Learn how to use events to expose delegate-based notifications safely while preventing unauthorized access and invocation.

We'll cover the following...

Exposing a public delegate field is risky because it allows external code to invoke the delegate, clear subscriptions, or inspect the invocation list. To prevent this, C# provides the event keyword.

Events wrap delegates to restrict access to the underlying delegate field. They provide only two actions to the outside world:

  • Subscribe: External classes can register themselves using +=.

  • Unsubscribe: External classes can remove themselves using -=.

The declaring class retains exclusive control over all other operations, such as invoking the delegate or clearing the list.

Use events

We can rewrite the FootballMatch example from the previous lesson using an event to secure our notification system.

The following code defines the event and the method that triggers it.