Boxing and Unboxing Types
Boxing
and unboxing are the
processes that enable value types (e.g., integers) to be treated as
reference types (objects). The value is
“boxed” inside an
Object, and subsequently
“unboxed” back to a value type. It
is this process that allows us to call the ToString( ) method on the integer in Example 5-4.
Tip
Java programmers take note: In Java, wrapping basic types in objects requires the explicit use of wrapper types like Integer and Float. In C#, the boxing mechanism takes care of all of this for you automatically; wrapper types are unnecessary.
Boxing Is Implicit
Boxing is an implicit conversion of a value type to the type
Object. Boxing a value allocates an instance of
Object and copies the value into the new object
instance, as shown in Figure 5-4.

Figure 5-4. Boxing reference types
Boxing is implicit when you provide a value type where a reference is
expected. For example, if you assign a primitive type, such as an
integer to a variable of type Object (which is
legal because int derives from
Object), the value is boxed, as shown here:
using System;
class Boxing
{
public static void Main( )
{
int i = 123;
Console.WriteLine("The object value = {0}", i);
}
}
Console.WriteLine( ) expects an object, not an
integer. To accommodate the method, the integer type is automatically
boxed by the CLR, and ToString( ) is called on the resulting object. This feature ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access