#657 – Boxing Makes a Copy of An Object

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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: