Tuesday, March 14, 2006

Delegates

I'm always confusing this...

For future reference;

  • Declare the delegate which defines the "class" for the event you're going to raise - with parameters etc
  • Declare the event - of type "delegate" - with the parameters.
  • Write a private function to handle calling the event - check for null event object first.
  • Then just call the private function whenever you want to raise the event.

public delegate void EventNameHandler(type paramName);

then;


public event EventNameHandler EventName;

then;


private void OnEventName(type param)
{
if (EventName != null)
    {
        EventName(param);
    }
}


Then, in the consuming class;


classWithTheEvent.EventName += new EventNameHandler(localFunctionName);