Events or Delegates?
On the face of it, events and delegates look remarkably similar:
- Events are an extended form of delegates.
- Both offer late-bound semantics, so rather than calling methods that are known precisely at compile-time, you can defer a list of target methods when known at runtime.
- Both are called using
Invoke()
or, more simply, the()
suffix shortcut, ideally with a null check before doing so.
The key considerations are as follows:
- Optionality: Events offer an optional approach; callers can decide to opt into events or not. If your component can complete its task without needing any subscriber methods, then it is preferable to use an event-based approach.
- Return types: Do you need to handle return types? Delegates associated with events are always void.
- Lifetime: Event subscribers typically have a shorter lifetime than their publishers, leaving the publisher to continue detecting new messages even if there are no active subscribers...