Raising custom events in C#

First you need to declare an event in the class that’s going to raise the event. This is just like declaring a normal variable:

  1. public event EventHandler MyEvent;

Then you need a method that’s going to be called to raise the event. This goes into the same class that you just declared the event in.

  1. protected virtual void OnMyEvent(EventArgs e) {
  2.     if(MyEvent != null) {
  3.         MyEvent(this, e);
  4.     }
  5. }

In the code where the event actually happens (say the code where a certain variable gets updated), you need to actually raise the event by calling the method we just created.

  1. MyVariable = newValue;
  2. OnMyEvent(EventArgs.Empty);

Then in the class that wants to listen for the event, you just register for it like you’d register for any of the built-in events:

  1. MyEventClass.MyEvent += new EventHandler(MyEventHandler);
  1. protected virtual void MyEventHandler(object sender, EventArgs e) {
  2.     // handle event
  3. }

C# and VB events links on the MSDN
Declaring, Raising and Handling events MSDN tutorial
Code Project example

Posted on 03 Nov 04 by Helen Emerson (last updated on 03 Nov 04).
Filed under .NET