Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unregister events with new instance of the delegate

Tags:

c#

events

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 writes Same! to the console.

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

After this code executes, is the EventHandler unregistered?

like image 515
Tarion Avatar asked Nov 21 '25 00:11

Tarion


1 Answers

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;
like image 61
Marc Gravell Avatar answered Nov 22 '25 17:11

Marc Gravell