views:

111

answers:

2

Say I have the following C# code:

Action a = TestMethod;
Action b = TestMethod;
Action c = b;
b += a;

Tests indicates that b is not the same instance as c, so clearly the + operator seems to create a new instance of the delegate. Is this a correct assumption? Does it reuse the b-instance internally, or does it just copy the method/target information to a new instance?

I seem to be unable to find the implementation of the + operator for delegates, the Delegate class doesn't seem to contain it.

Can anyone shed some light on this issue?

The reason I'm asking is that I'm creating some classes that will layer themselves around each other like onions, and the outermost layer will call an inner layer, obtain some delegates and then attach more methods to those delegates, I'm just concerned that doing so will in some way change the delegates I obtain from the inner layer, in which case I need to return copies/clones, instead of just the internal references.

Note that this is wholly internal code to my library, so while I know that passing out internal data structures like that is a bad idea generally, if I can do it safely with these classes, then I will do so.

+4  A: 

+= is equivalent to Delegate.Combine(). -= is equivalent to Delegate.Remove(). Each creates a new Delegate instance and returns it.

HTH, Kent

Kent Boogaart
+4  A: 

As Kent says, += uses to Delegate.Combine, and -= uses Delegate.Remove. See my events/delegates article for more information.

The important thing is that delegates are immutable - calling Combine/Remove doesn't change the delegate you call it on at all - so you don't need to clone anything. The same is true for anything else you do with the delegate: if you get the invocation list and change the contents of the returned array, for example, that won't change what the delegate actually does.

(This is just like String's behaviour, if you want another way of thinking about it.)

Jon Skeet
Thanks, that simplifies everything.
Lasse V. Karlsen