Thursday, October 12, 2006

Boxing And Value Types

Here is an interesting aspect with regard to boxing of valye type.

int i = 232;
Console.WriteLine("This is boxed: {0}", i);
Console.WriteLine("This is not boxed: {1}", i.ToString());

Its intersting to note that in first Writeline function boxing occurs while in second it doesnt. Reason ?? simple. Writeline expects its second parameter to be object and hence in the first case , "i" is boxed.

But in the second case, we are converting i to string using the ToString Function. This results in a reference to the string to be returned and not the value type. Hence no boxing occurs in this statement.

A look at the IL code of same, would reconfirm the fact. The IL code for the above statements in shown below.

.locals init ([0] int32 i)
IL_0000: ldc.i4 0x913
IL_0005: stloc.0
IL_0006: ldstr "This is boxed: {0}"
IL_000b: ldloc.0
IL_000c: box [mscorlib]System.Int32
IL_0011: call void [mscorlib]System.Console::WriteLine(string,object)
IL_0016: ldstr "This is not boxed: {1}"
IL_001b: ldloca.s i
IL_001d: call instance string [mscorlib]System.Int32::ToString()
IL_0022: call void [mscorlib]System.Console::WriteLine(string,object)
IL_0027: ret