Wordsmyth's Corner

How to Create a Custom Event

Explains how to create custom events and handlers in C#.

General Example

class Thrower
{
 
 // Declare an event.  The first parameter is the 
 // name of the delegate type for methods that handle 
 // the event.  The second name is the event name.

 public event EventDelegate EventName;

 // Declare the delegate for the handler.  In this simple example,
 // the only argument is a string.  If the arguments are more complex,
 // it's probably better to create a class: EventNameArgs

 public delegate void EventDelegate (string argString);

 // Raise the event when appropriate.  Make sure to check
 // for null or else it'll fail if there are no subscribers.
 // If the event is raised from a lot of places, or requires
 // an EventArgs class, it's usually best to create a helper
 // method to build and send the event.

 public void SomeMethod()
    {
    if (EventName!= null)
       {
       EventName("hello");
       } 
     }
}

class Catcher
{

  // Subscribe to the event.  This requires creating a 
  // new delegate instance.

  public Catcher()
  {
  myThrower.EventName += new Thrower.EventDelegate(EventHandler);
  }

  // Implement the event handler.  Prototype must match
  // the prototype for EventDelegate.

  void EventHandler(string argString)
  {  
  }
}

Specific Example

class Remote
{
 
 public event CriticalErrorHandler CriticalErrorEvent;
 public delegate void CriticalErrorHandler(Exception exception);

 public void SomeMethod(Exception exception)
    {
    if (CriticalErrorEvent != null)
       {
       CriticalErrorEvent(exception);
       } 
     }
}

class MainForm
{
  public MainForm()
  {
  g_remote.CriticalErrorEvent += new Remote.CriticalErrorHandler(HandleCriticalError);
  }

  void HandleCriticalError(Exception exception)
  {  
  MessageBox.Show("EXCEPTION! " + exception.ToString());
  }
}