3

Consider the following:

Action<int, T> a1 = new Action<int, T>(_insert);

Action<int, T> a2 = new Action<int, T>(a1);

What is a2 referring to ? Is it a1, a shallow copy of a1 or is it a deep copy of a1 ?

usr
  • 168,620
  • 35
  • 240
  • 369
marc wellman
  • 5,808
  • 5
  • 32
  • 59

1 Answers1

4

a2 is referencing a1. Here is the IL:

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 3
    .locals init (
        [0] class [mscorlib]System.Action a1,
        [1] class [mscorlib]System.Action a2)
    L_0000: nop 
    L_0001: ldnull 
    L_0002: ldftn void WebTools.ConsoleTest.Program::Main()
    L_0008: newobj instance void [mscorlib]System.Action::.ctor(object, native int)
    L_000d: stloc.0 
    L_000e: ldloc.0 
    L_000f: ldftn instance void [mscorlib]System.Action::Invoke() #1
    L_0015: newobj instance void [mscorlib]System.Action::.ctor(object, native int)
    L_001a: stloc.1 
    L_0020: nop 
    L_0021: ret 
}

At #1 the IL code is referencing a1's Invoke method and the instance a1 itself.

A shallow copy would mean that the contents of a1 are copied, but nothing is being copied. The object a1 is treated as a black-box. Therefore a2 will keep a1 alive with respect to GC.

usr
  • 168,620
  • 35
  • 240
  • 369
  • Thank you ! p.s.: I am still working on my UI flooding issue (from [here](http://stackoverflow.com/questions/11320156/when-is-the-gui-overloaded) and [here](http://stackoverflow.com/questions/11250947/assist-the-ui-dispatcher-to-handle-a-flood-of-method-invocations)) and as soon I solved it I let you know via comment :) – marc wellman Jul 08 '12 at 09:34
  • For me, your answer stirs up more questions than it answers. My reading of this IL listing is that `b` [sic] references `a.Invoke` and not whatever method(s) `a` references. Thus it comes closest to being a shallow copy. Saying that it`s another level of indirection might be more accurate. – stakx - no longer contributing Jul 08 '12 at 09:36
  • @stakx, A shallow copy would mean that the *contents* of a1 are copied, but nothing is being copied. The object a1 is treated as a black-box. Therefore a2 will keep a1 alive with respect to GC. – usr Jul 08 '12 at 09:39
  • @stakx To be honest I am not familiar with IL .. so you think this is somehow incorrect (in case it is I would reject my accepted answer - just to not provide wrong answers to the SO community) – marc wellman Jul 08 '12 at 09:41
  • 1
    @usr, exactly (even though GC is mostly irrelevant to this question)! Thanks for adding that clarification to your answer. – stakx - no longer contributing Jul 08 '12 at 09:47