Search⌘ K
AI Features

Events

Explore how events in C# enhance delegate security by restricting external invocation and subscription management. Learn to declare events, use the event keyword, and implement custom add and remove accessors to control subscriber behavior. Understand safe invocation and best practices for event handling in modern C# development.

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 ...