As you can see in the question posted by @Oded:
An Event declaration adds a layer of abstraction and protection on the
delegate instance. This protection prevents clients of the delegate
from resetting the delegate and its invocation list and only allows
adding or removing targets from the invocation list.
This is needed because, using delegates and events, two roles appear: the broadcaster and the subscriber.
From the "C# 4 in a Nutshell" book:
The broadcaster is a type that contains a delegate field. The
broadcaster decides when to broadcast, by invoking a 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.
Then, an event is a construct used to expose the delegate features required for this model, the subscriber/broadcaster model. The main purpose of events is to prevent subscribers from interfering with each other.
For example:
Consider a friend and yourself. You sign an agreement with your friend. This agreement consists of:
- When you have finished doing an activity, your friend has to inform
other friends about the end of your activity. Those friends have to
do other activities.
In this case, you are the broadcaster, your friend is a subscriber, the end of your activity is the event. What about the delegate? The delegate is your friend, because he has to give the news to other friends about the end of your activity, in order to let them doing other activities.
In other terms:
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) /* if invocation list is not empty, fire the event */
PriceChanged(price, value);
price = value;
}
}
You can see that the Stock
class fires its PriceChanged
event every time the Price
of the Stock
changes.