Search code examples
c#arraysboxing

Array of integers boxing


Let's say I have an array of integers and attempt to do a call to CopyTo() onto a different array:

int[] a = {1, 2, 3};
int[] b = new int[3];

a.CopyTo(b, 0); // does b have a completely new set of { 1, 2, 3 }?

CopyTo() does a shallow copy, but I'm wondering, since int[] is a reference type, would this cause the elements within a to become boxed and thus no longer be value types?


Solution

  • Since you've created a new instance for array b

    int[] b = new int[3];
    

    the answer for your first question

    does b have a completely new set of { 1, 2, 3 }?

    is yes; b doesn't share the reference with a:

    // false - a and b are different instances
    // even if then can have same items they don't share the same reference
    Console.Write(ReferenceEquals(a, b));
    

    Since you've created b as an array of int - int[] there will be no boxing.; all the items will be copied by values. If you want to play with boxing make b keep items by reference: object[] b = new object[3];; if you want to see shallow copy make both arrays objects[]:

    // boxed items
    object[] a = new int[] { 1, 2, 3 };
    
    // boxed items
    object[] b = new object[3];
    
    // references to boxed integers will be copied 
    a.CopyTo(b, 0);
    
    // True
    Console.WriteLine(ReferenceEquals(a[0], b[0]));
    
    // Let's demonstrate that a[0] and b[0] share the same reference:
    // We change a[0] and we get b[0] changed as well:
    
    // boxed values don't expose their inner data, let's use Reflection
    a[0].GetType()
        .GetField("m_value", BindingFlags.Instance | BindingFlags.NonPublic)
        .SetValue(a[0], 456);
    
    // 456
    Console.WriteLine(b[0]);