What is the difference between a delegate and an event?
Quick Answer
An event is a delegate field with restricted access: outside code can only += / -= to it — it can't invoke it or reassign it (= null). Only the declaring class can raise the event. A raw public delegate field gives callers all of that power, which is usually a design mistake.
An event is essentially a delegate with a protective wrapper around it. If I expose a public delegate field, any code can not only subscribe but also invoke it or set it to null, wiping out everyone else's handlers. An event only lets external code add and remove handlers — raising it is private to the declaring class. So it's a delegate with the dangerous operations locked down, which is why you always use event for the publish-subscribe pattern rather than a bare delegate.
- Convention:
public event EventHandler<OrderEventArgs> OrderPlaced;; raise via a protectedOnOrderPlacedmethod with a null-check (OrderPlaced?.Invoke(this, args)). - Events can have custom
add/removeaccessors (e.g. thread-safe subscription, weak events). - Remember to unsubscribe (
-=) or you leak the subscriber.