How do I pass objects in EventArgs

GPGVM picture GPGVM · Feb 20, 2013 · Viewed 62.7k times · Source

I have a usercontrol that raises an event after communicating with a web service. The parent handles this event when raised. What I thought would be the proper approach would be to pass the object returned from the webservice to the parent as eventargs???

If this is the proper way I can't seem to find the instructions on how to do so.

UserControl

public event EventHandler LoginCompleted;

then later after the service returns biz object:

if (this.LoginCompleted != null)
        {
            this.LoginCompleted(this, new EventArgs() //this is where I would attach / pass my biz object no?);  
        }

Parent

ctrl_Login.LoginCompleted += ctrl_Login_LoginCompleted;
....snip....
void ctrl_Login_LoginCompleted(object sender, EventArgs e)
    {
        //get my object returned by login
    }

So my question is what would be the "approved" method for getting the user object back to the parent? Create a property class that everything can access and put it there?

Answer

Daniel Hilgarth picture Daniel Hilgarth · Feb 20, 2013

You would have to declare your event using EventHandler<T> where T is your class that derives from EventArgs:

public event EventHandler<LoginCompletedEventArgs> LoginCompleted;

LoginCompletedEventArgs could look like this:

public class LoginCompletedEventArgs : EventArgs
{
    private readonly YourBusinessObject _businessObject;

    public LoginCompletedEventArgs(YourBusinessObject businessObject)
    {
        _businessObject = businessObject;
    }

    public YourBusinessObject BusinessObject
    {
        get { return _businessObject; }
    }
}

Usage would be like this:

private void RaiseLoginCompleted(YourBusinessObject  businessObject)
{
    var handler = LoginCompleted;
    if(handler == null)
        return;

    handler(this, new LoginCompletedEventArgs(businessObject));
}

Please notice how I implemented RaiseLoginCompleted. This is a thread-safe version of raising the event. I eliminates a possible NullReferenceException that can occur in a race condition scenario where one thread wants to raise the event and another thread un-subscribes the last handler after the if check but before actually invoking the handler.