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