Friday, December 07, 2007

Raising an event in C#

Here is the simplest way to raise an event.


public class TestEvent{
public event EventHandler MyEvent;
public void RaiseMyEvent(){
MyEvent(this, null);
}
}


This uses the default EventHandler that returns a object source and a EventArgs ex. If you want to pass back different parameters, you will need to create your own delegate. The delegate we just used looks like this:

public delegate void EventHandler (object source, EventArgs ex);



We dont have to define it because .NET already defined it for us. Here is a second example where we built a custom delegate and raise it.


public delegate void MyCustomEventHandler (string message);

public class TestEvent2{
public event MyCustomEventHandler MyEvent2;
public void RaiseMyEvent(){
MyEvent2("Message sent with event");
}
}


Now that I explained how to raise events, there is a bug in that code. I'm saving that for my next post: NullReferenceException raising an event in C#

No comments: