Delegates and Events in C# - Events
(Page 2 of 4 )
When using delegates, two emergent roles commonly appear: broadcaster and subscriber.
The broadcaster is a type that contains a delegate field. The broadcaster 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. Aneventis 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 each other.
To declare an event member, you put theevent keyword in front of a delegate member. For instance:
public class Broadcaster
{
public event ProgressReporter Progress;
}
Code within theBroadcastertype has full access toProgressand can treat it as a delegate. Code outside ofBroadcastercan only perform+=and-=operations onProgress.
Consider the following example. TheStockclass invokes itsPriceChangedevent every time thePriceof theStock 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 PriceChanged PriceChanged;
public decimal Price
{
get { return price; }
set
{
if (price == value) return; // exit if nothing has changed
if (PriceChanged != null) // if invocation list not empty
PriceChanged (price, value); // fire event
price = value;
}
}
}
If we remove theeventkeyword from our example so thatPriceChangedbecomes an ordinary delegate field, our example would give the same results. However,Stockwould be less robust, in that subscribers could do the following things to interfere with each other:
- Replace other subscribers by reassigningPriceChanged(instead of using the+=operator).
- Clear all subscribers (by settingPriceChangedtonull).
- Broadcast to other subscribers by invoking the delegate.
Next: Standard Event Pattern >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|