#657 – Boxing Makes a Copy of An Object
August 27, 2012 Leave a comment
When you pass a value-typed object to a function that accepts a parameter of type object, the value-typed object is boxed. That is, it is copied into a temporary reference-typed object, which is actually passed into the function. This boxing happens automatically.
If we look at an object that represents a boxed value type, we’ll see that its reported type is the value type.
static void Test(object o) { Console.WriteLine(string.Format("Value = {0}, Type = {1}", o, o.GetType())); } static void Main() { int x = 12; Test(x); }
However, if we try changing the object within the method, the original int that was passed in is unaffected.
static void Test(object o) { Console.WriteLine(string.Format("Value = {0}, Type = {1}", o, o.GetType())); o = 100; } static void Main() { int x = 12; Test(x); Console.WriteLine(string.Format("After call, x = {0}", x)); }
The boxed object is passed into the function using value type semantics.