bartosz.baczek bartosz.baczek - 1 year ago 74
C# Question

What is the point of using EventHandler like that?

What is the use of unregistering event handler that is not added yet in the code below?

public class foo
private event EventHandler<boo> booCompleted;

public RegisterBooCompletedHandler(EventHandler<boo> newBooCompletedEventHandler, bool forceUnregisterOtherEventHandlers)
if (forceUnregisterOtherEventHandlers)
booCompleted = null

booCompleted -= newBooCompletedEventHandler; // <- why do we unregister not added yet event handler?
booCompleted += newBooCompletedEventHandler;

Answer Source

It means that if you call RegisterBooCompletedHandler(handler) multiple times with the same handler, you still only actually subscribe to the event once for that handler.

My guess is that actually you've seen this due to someone working round a problem where really they were subscribing to the event in the wrong place, and so subscribing multiple times... but I'm sure there are some cases where it's hard to know whether you've already subscribed or not, and just making it a (nearly) no-op to subscribe again is convenient.

I say it's a "(nearly) no-op" because it changes the ordering. Consider:

// After this call, invocation list is A
RegisterBooCompletedHandler(A, false);
// After this call, invocation list is A, B
RegisterBooCompletedHandler(B, false);
// After this call, invocation list is A, B, C
RegisterBooCompletedHandler(C, false);
// After this call, invocation list is A, C, B
RegisterBooCompletedHandler(B, false);