How events are more robust than delegates

Consider the following example.

The Stock class fires 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; // Exit if nothing has changed
            if (PriceChanged != null) // If invocation list not empty,
            PriceChanged (price, value); // fire event.
            price = value;
        }
    }
}

If we remove the event keyword from our example so that PriceChanged becomes an ordinary delegate field, our example would give the same results. However, Stock would be less robust,

My question is in what way the event keyword makes the stock more robust?

Jon Skeet
people
quotationmark

My question is in what way the event keyword makes the stock more robust?

It's all a matter of what clients outside the class can do. If this were just a public field, then anyone could:

  • Call all existing handlers themselves
  • Remove/replace all existing handlers

Instead, by using an event, other code can only subscribe to the event or unsubscribe from it. I wouldn't use the word "robust" to describe this difference - it's a matter of encapsulation, and expressing what other code should be able to do with an instance of Stock.

See my article on delegates and events for more information.

people

See more on this question at Stackoverflow