[HowTo] 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:

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.

protected virtual void OnMyEvent(EventArgs e) 
{
     if(MyEvent != null)  
            MyEvent(this, e);
}

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.

    MyVariable = newValue;
    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:

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

or
@Microsoft
@dreamincode


Leave a Reply