#220 – Boxing Can Happen Automatically

Boxing can happen automatically in C#, when you pass a value-typed variable to a method that accepts a System.Object (object).

The Console.WriteLine method is a good example of this.  It accepts a format string as its first parameter and then a series of object parameters, which represent objects to substitute into the format string.  (Specifically, Console.WriteLine calls each object’s ToString method to get its string representation).

We can pass in some reference-typed objects to Console.WriteLine.

            Person p = new Person("Lillian", "Gish");

            Console.WriteLine("The actor known as {0} was a silent film star.", p);

We can also pass value-typed variables into Console.WriteLine.  The value types will be boxed–converted into reference types.  An object will be created on the heap for each value-typed parameter and its value copied to the new object.

            int i = 1964;

            Console.WriteLine("Favorite numbers: {0}, {1}, {2}", 42, 6, i);
Advertisements

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

One Response to #220 – Boxing Can Happen Automatically

  1. Pingback: #657 – Boxing Makes a Copy of An Object « 2,000 Things You Should Know About C#

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: