C# Custom Event Handlers

Here’s a quick example for creating custom event handlers in C#.

We start by creating our EventArgs object. This should inherit from the standard EventArgs class, and include the properties we want to pass when the event is fired:

public class OpenEventArgs : EventArgs
{
  public string FileName { get; set; }
}

Next, the signature of the event handler is defined:

public delegate void OpenEventHandler(object sender, OpenEventArgs e);

The event itself is defined using the new event handler delegate:

public event OpenEventHandler Opened;

Although not essential, it’s a good idea to write a method for firing the event. This only needs to be visible to our class and any inheriting class, so its marked protected. The additional of the virtual keyword allows inheriting classes to override the method.

protected virtual void OnOpened(OpenEventArgs e)
{
  if (Opened != null)
    Opened(this, e);
}

To raise the event just call OnOpened, passing an instance of the OpenEventArgs class:

public void Open(string fileName)
{
  // Open file
  // ...

  // Raise event
  OpenEventArgs args = new OpenEventArgs();
  args.FileName = fileName;
  OnOpened(args);
}

The complete code should resemble this:

public class MyClass
{
  public event OpenEventHandler Opened;
  public delegate void OpenEventHandler(object sender, OpenEventArgs e);

  public void Open(string fileName)
  {
    // Open data
    // ...

    // Raise event
    OpenEventArgs args = new OpenEventArgs();
    args.FileName = fileName;
    OnOpened(args);
  }

  protected virtual void OnOpened(OpenEventArgs e)
  {
    if (Opened != null)
      Opened(this, e);
  }
}

public class OpenEventArgs : EventArgs
{
  public string FileName { get; set; }
}
Advertisements
This entry was posted in Reference and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s