Search code examples
c#.netboxingunboxing

What happens in this Boxing example in C#?


Jon Skeet, has an interesting post titled: "Why boxing doesn't keep me awake at night" where he benchmarks the performance of different ways of outputting an integer value.

I am pretty sure the code below IS boxing, but why Jon is considering it NOT to be boxing? his example is at the end.

int i = 5;
object o = i;
Console.WriteLine("Number is: {0}", o);

The example from Jon's page:

#if CONSOLE_WITH_BOXING
            Console.WriteLine("{0} {1} {2}", i, i, i);            
#elif CONSOLE_NO_BOXING
            object o = i;
            Console.WriteLine("{0} {1} {2}", o, o, o);
#elif CONSOLE_STRINGS
            string s = i.ToString();
            Console.WriteLine("{0} {1} {2}", s, s, s);

P.S. "boxing and unboxing in int and string" does not answer my question.

Thank you.


Solution

  • It is boxing, the only difference is on what line it is happening:

    not boxing (see http://msdn.microsoft.com/en-us/library/a0bfz20d%28v=vs.110%29.aspx):

    Console.WriteLine("{0} {1} {2}", o, o, o);
    

    boxing:

    object o = i;
    

    or consider

    three boxing(s):

    Console.WriteLine("{0} {1} {2}", i, i, i);
    

    one boxing:

    object o = i;
    Console.WriteLine("{0} {1} {2}", o, o, o);