tags:

views:

896

answers:

2

I am looking to pass an event to a helper function. This function will attach a method to the event. However, I am having trouble properly passing the event. I have tried passing a EventHandler<TEventArgs>. It compiles, but events are not attached (but are still added; it seems a copy of the event handler is made).

For example, if I have this:

public event EventHandler<EventArgs> MyEvent;

And the helper function:

public static void MyHelperFunction<TEventArgs>(EventHandler<TEventArgs> eventToAttachTo)
{
    eventToAttachTo += (sender, e) => { Console.WriteLine("Hello world"); };
}

And the caller:

MyHelperFunction(MyEvent);
MyEvent(null, new EventArgs()); // Does nothing.
A: 

Just guessing: Have you tried passing it as ref?

public static void MyHelperFunction<TEventArgs>(ref EventHandler<TEventArgs> eventToAttachTo)

MyHelperFunction(ref MyEvent);
Michael Stum
+5  A: 

The reason why this does not work is += when applied to a delegate creates a new delegate which is the combination of the old and the new. It does not modify the existing delegate.

In order to get this to work you will have to pass the delegate by reference.

public static void Helper(ref EventHandler<EventArgs> e)
{
    e+= (x,y) => {};
}

The reason this works outside of the method is because the LHS is still the actual field. So += will create a new delegate and assign back to the member field.

JaredPar
Interesting. So I guess += recreates the delegate (like e = e + func). Thanks for your help! Spent several hours trying to debug my code (blaming it on threading) when in fact an event wasn't being fired when it should have.
strager
@strager, When you hit situations like this, it's a good idea to whip out Reflector. It will un-wind some misleading syntax constructs and show you what's actually happening.
JaredPar
A problem with using ref: I get the following error if I use Helper(ref myClassInstance.MyEvent): The event MyEvent can only appear on the left hand side of += or -= (except when used from within the type MyClass). How can I work around this?
strager
To note, I am doing this only in my unit test (so I can use internal, I think), but it'd be nice to have a clean public solution as well.
strager
I have this same problem. did you find a way around the left side error?
Jason Coyne
I'm also getting the left hand side error as well. Could you provide an example of the usage of your static Helper class?
Secret Agent Man