Pass a return value back through an EventHandler

Leroy Jenkins picture Leroy Jenkins · Sep 18, 2009 · Viewed 67.5k times · Source

Im trying to write to an API and I need to call an eventhandler when I get data from a table. Something like this:

    public override bool Run(Company.API api)
    {
        SomeInfo _someInfo = new SomeInfo();

        if (_someInfo.Results == 1)
            return true;
        else
            return false;

        using (MyTable table = new MyTable(api))
        {
            table.WhenData += new EventHandler<DataEventArgs<Record>>(table_WhenData);
            table.WhenDead += new EventHandler<EventArgs>(table_WhenDead);
            table.Start();
        }

    public void table_WhenData(object sender, DataEventArgs<Record> e)
    {
        return true;
    }

The problem that Im having is I dont know how to pass a return value back from table_WhenData to the Run method.

Ive tried many ways (like trying to pass _someInfo to the method) but I just cant seem to get the syntax right.

Any suggestion is greatly appreciated.

Answer

JoshBerke picture JoshBerke · Sep 18, 2009

The common pattern here is not to return any data from the event handler, but to add properties to your event argument object so that the consumer of the event can set the properties which the caller can then access. This is very common in UI handling code; you see the Cancel event concept all over the place.

The following is pseudo code, and not compile ready. Its intent is to show the pattern.

public class MyEventArgs : EventArgs
{
   public bool Cancel{get;set;}
}

public bool fireEvent()
{
    MyEventArgs e=new MyEventArgs();

    //Don't forget a null check, assume this is an event
    FireEventHandler(this,e);

    return e.Cancel;
}

public HandleFireEvent(object sender, MyEventArgs e)
{
 e.Cancel=true;
}

Edit

I like how Jon Skeet worded this: make the EventArgs mutuable. That is, the consumer of the event can modify the state of the EventArgs object allowing for the raiser of the event to get to that data.