string symbol; decimal price; public Stock (string symbol) {this.symbol = symbol;} public event EventHandler PriceChanged; protected virtual void OnPriceChanged (EventArgs e) { if (PriceChanged != null) PriceChanged (this, e); }
}
public decimal Price { get { return price; } set { if (price == value) return; price = value; OnPriceChanged (EventArgs.Empty); } }
Note that we also used the EventArgs.Empty property—this saves instantiating an instance of EventArgs.
Event Accessors An event’s accessors are the implementations of its += and −= functions. By default, accessors are implemented implicitly by the compiler. Consider this event declaration: public event EventHandler PriceChanged;
The compiler converts this to the following: • A private delegate field. • A public pair of event accessor functions, whose implementations forward the += and −= operations to the private delegate field. You can take over this process by defining explicit event accessors. Here’s a manual implementation of the PriceChanged event from our previous example:
Events | 111