Chapter 16 Quick Reference
To | Do this |
Declare a delegate type. | Write the keyword delegate, followed by the return type, followed by the name of the delegate type, followed by any parameter types. For example:
delegate void Tick(); |
Invoke a delegate. | Use the same syntax as a method call. For example:
Tick m; ... m(); |
Create an instance of a delegate. | Use the same syntax you use for a class or struct: write the keyword new, followed by the name of the type (the name of the delegate), followed by the argument between parentheses. The argument must be a method whose signature exactly matches the signature of the delegate. For example:
delegate void Tick(); private void Method() { ... } ... Tick m = new Tick(this.Method); |
Declare an event. | Write the keyword event, followed by the name of the type (the type must be a delegate type), followed by the name of the event. For example:
delegate void TickHandler(); class Ticker { public event TickHandler Tick; } |
Subscibe to an event. | Create a delegate instance (of the same type as the event), and attach the delegate instance to the event by using the += operator. For example:
class Clock { ... public void Start() { ticker.Tick += new TickHandler (this.RefreshTime); } private void RefreshTime() { ... } private Ticker ticker = new Ticker(); } You can also get the compiler to automatically generate the new delegate by just specifying the subscribing method:
public void Start() { ticker.Tick += this.RefreshTime; } |
Unsubscribe from an event. | Create a delegate instance (of the same type as the event), and detach the delegate instance from the event by using the –= operator. For example:
class Clock { ... public void Stop() { ticker.Tick - = new TickHandler (this.RefreshTime); } private void RefreshTime() { ... } private Ticker ticker = new Ticker(); }
Or:
public void Stop() { ticker.Tick -= this.RefreshTime; } |
Raise an event. | Use parentheses exactly as if the event were a method. You must supply arguments to match the type of the event. Don't forget to check whether the event is null. For example:
class Ticker { public event TickHandler Tick; ... private void Notify() { if (this.Tick != null) { this.Tick(); } } ... } |