Boxing and Unboxing Types

Even the simple value types like int in C# can be thought of as objects. In fact, there are formal terms for the conversion of value types into reference types (that is, objects) and back again—boxing and unboxing.

Boxing a value type is the conversion of that value type into the type object. Boxing is implicit, which means the compiler will do it for you. For example, say you pass an integer to WriteLine in this code, where temperature is an int variable:

System.Console.WriteLine("The temperature is {0}", temperature);

In the case where you use a format string with WriteLine, WriteLine is actually expecting you to pass an object after the format string. When you pass an int, C# will box it into an object, and call ...

Get Microsoft® Visual C#® .NET 2003 Kick Start now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.