Tuesday, February 10, 2009

Boxing

int i = 1;
object o = i;
o = 10;
Console.WriteLine("{0},{1}", i, o);
//Prints 1,10

So basically, when you box, a copy of your value type is made and stored in the reference type.

Also, Console.WriteLine() does not take int – it takes object, so when an int is passed, it will be boxed before printing. So it is better to use ToString() on value types.

int i = 1;
object o = i;
o = 10;
Console.WriteLine("{0},{1}", i.ToString(), o);
//Prints 1,10

No comments: