Information Technology Reference
In-Depth Information
System.Object
Interface
Reference Type Container
(The Box)
Allocated on the Heap
Value Type
Contained in the Box
Pass Through
Mirror Value Type Interface
Figure 6.1 Value type in a box. To convert a value type into a System.Object
reference, an unnamed reference type is created. The value type is stored
inline inside the unnamed reference type. All methods that access the
value type are passed through the box to the stored value type.
In many ways, the addition of generics in .NET 2.0 means that you can
avoid boxing and unboxing simply by using generic classes and generic
methods. That is certainly the most powerful way to create code that uses
value types without unnecessary boxing operations. However, there are
many locations in the .NET Framework where methods have parameters
typed as System.Object. Those APIs will still produce boxing and unbox-
ing operations. It happens automatically. The compiler generates the box-
ing and unboxing instructions whenever you use a value type where a
reference type, such as System.Object, is expected. In addition, the boxing
and unboxing operations occur when you use a value type through an
interface pointer. You get no warnings—boxing just happens. Even a sim-
ple statement such as this performs boxing:
Console .WriteLine( "A few numbers:{0}, {1}, {2}" ,
25 , 32 , 50 );
The referenced overload of Console.WriteLine takes an array of System
.Object references. ints are value types and must be boxed so that they can
be passed to this overload of the WriteLine method. The only way to coerce
the three integer arguments into System.Object is to box them. In addition,
inside WriteLine, code reaches inside the box to call the ToString() method
of the object in the box. In a sense, you have generated this construct:
Search WWH ::




Custom Search