tags:

views:

382

answers:

2
EventHandler a = new EventHandler(control_RegionChanged);
EventHandler b = new EventHandler(control_RegionChanged);

 if (a == b)
 {
     Console.WriteLine("Same!");
 }
 else
 {
     Console.WriteLine(a.GetHashCode() + " " + b.GetHashCode());
 }

This wirte "Same!" to the console.

control.RegionChanged += new EventHandler(control_RegionChanged);
control.RegionChanged -= new EventHandler(control_RegionChanged);

After this code the event is still unregistered? I think the answer is simply yes. But maybe this helps someone who has the same question.

A: 

Try using

control.RegionChanged += control_RegionChanged
control.RegionChanged -= control_RegionChanged

This should also work (from memory -- haven't really tested it). At least it doesn't create a new eventhandler-reference.

Lennaert
Actually it does. The compiler does it for you.
Samuel
I just tested it, and -- at least in my test -- after adding and removing the handler this way, it works.
Lennaert
This is simply shorthand, which the compiler still turns into a new EventHandler.
J. Steen
@Lennaert: Of course it works, I never said it didn't. I said your last sentence is wrong.
Samuel
+4  A: 

Yes; delegates are compared on the instance and MethodInfo; if those are the same, then it will work. The problem comes when trying to unsubscribe an anonymous method; in that case, you must keep a reference to the delegate in order to unsubscribe.

So:

This is fine:

control.SomeEvent += obj.SomeMethod;
//...
control.SomeEvent -= obj.SomeMethod;

But this is much riskier:

control.SomeEvent += delegate {Trace.WriteLine("Foo");};
//...
control.SomeEvent -= delegate {Trace.WriteLine("Foo");};

The correct process with anonymous methods is:

EventHandler handler = delegate {Trace.WriteLine("Foo");};
control.SomeEvent += handler;
//...
control.SomeEvent -= handler;
Marc Gravell