O'Reilly logo

C# 3.0 Pocket Reference, 2nd Edition by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 != null) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required