65.9K
CodeProject is changing. Read more.
Home

Basic Event Creation in C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.20/5 (5 votes)

Sep 3, 2010

CPOL
viewsIcon

12270

A few quick examples of how to correctly create events.

The Basic Event Pattern

Creating an event is a simple process. Declare the event using the event keyword and create a suitable method to raise it.

public class YourClass
{
    // The Xxx event
    public event EventHandler Xxx;

    // The method you will call to raise the event.
    protected virtual void OnXxx(EventArgs e)
    {
        // Create a copy of the event to avoid a potential race condition
        // between the null check and raising the event.
        EventHandler eh = Xxx;
        // eh will be null if no subscribers so we need to test here.
        if (eh != null)
            // We have at least one subscriber so fire away!
            eh(this, e);
    }
}

Passing Data

This is also simple. We just need to create a modified EventArgs and EventHandler.

Here we will pass an integer.

// Derive from EventArgs
public class XxxEventArgs : EventArgs
{
    private int value;

    public XxxEventArgs(int value)
    {
        this.value = value;
    }

    public int Value
    {
        get { return value; }
    }
}
public delegate void XxxEventHandler(object sender, XxxEventArgs e);

In Use:

public class YourClass
{
    // The event, using our handler.
    public event XxxEventHandler Xxx;

    // The method you will call to raise the event, taking an instance of our args class.
    protected virtual void OnXxx(XxxEventArgs e)
    {
        // Our handler
        XxxEventHandler eh = Xxx;
        if (eh != null)
            eh(this, e);
    }
}

Passing More Complex Data

To return more complex information or multiple objects, simply create a suitable EventArgs derived class and delegate. In fact, you can avoid creating your own delegate by using the generic version of EventHandler!

Here's an example:

public class GotDataEventArgs : EventArgs
{
    private byte[] data;
    private int id;
    private string name;
    private DateTime timeStamp;

    public GotDataEventArgs(byte[] data, int id, string name)
    {
        this.data = data;
        this.id = id;
        this.name = name;
        timeStamp = DateTime.Now;
    }

    public byte[] Data
    {
        get { return data; }
    }
    public int ID
    {
        get { return id; }
    }
    public string Name
    {
        get { return name; }
    }
    public DateTime TimeStamp
    {
        get { return timeStamp; }
    }
}
public class YourClass
{
    public event EventHandler<GotDataEventArgs> GotData;

    protected virtual void OnGotData(GotDataEventArgs e)
    {
        EventHandler<GotDataEventArgs> eh = GotData;
        if (eh != null)
            eh(this, e);
    }
}

Conclusion

There is a lot more that can be done with events such as cancelable or asynchronous events, but the above examples will cover 99% of use cases.