#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);

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers