Events

When using delegates, two emergent roles commonly appear: broadcaster and subscriber.

The broadcaster is a type that contains a delegate field. It decides when to broadcast by invoking the delegate.

The subscribers are the method target recipients. A subscriber decides when to start and stop listening by calling += and -= on the broadcaster’s delegate. A subscriber does not know about, or interfere with, other subscribers.

Events are a language feature that formalizes this pattern. An event is a wrapper for a delegate that exposes just the subset of delegate features required for the broadcaster/subscriber model. The main purpose of events is to prevent subscribers from interfering with one another.

To declare an event member, you put the event keyword in front of a delegate member. For instance:

	public class Broadcaster
	{
	  public event ProgressReporter Progress;
	}

Code within the Broadcaster type has full access to Progress and can treat it as a delegate. Code outside of Broadcaster can only perform += and -= operations on Progress.

Consider the following example. The Stock class invokes its PriceChanged event every time the Price of the Stock changes:

	public delegate void PriceChangedHandler
	  (decimal oldPrice, decimal newPrice);

	public class Stock
	{
	  string symbol;
	  decimal price;

	  public Stock (string symbol) {this.symbol = symbol;}
	  public event PriceChangedHandler PriceChanged; public decimal Price { get { return price; } set { if (price == value) return; if (PriceChanged != ...

Get C# 3.0 Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.