November 11, 2008

Delegating an Event Handler

// Say we have some event declared in one class
public event SomeStatusEventHandler SomeStatusEvent
{   // Delegate the event 'add' and 'remove' calls to the 'target' object
 add { this.target.SomeStatusEvent += value; }
 remove { this.target.SomeStatusEvent -= value; }
}
There is a sample of this in use in the Windows Service Class Example. Note that this syntax exposes an event for adding and removing event handlers but an event must be defined elsewhere that is to be exposed.
Say we have some private event declared in the same class:
private event SomeStatusEventHandler someStatusEvent;

public event SomeStatusEventHandler SomeStatusEvent
{   
 add { this.SomeStatusEvent += value; }
 remove { this.SomeStatusEvent -= value; }
}

No comments: