Information Technology Reference
In-Depth Information
6
Miscellaneous
Some items don't fit convenient categories. But that does not limit their
importance. Understanding exception-handling strategies is important for
everyone. Other recommendations are constantly changing because C# is
a living language, with an active community and an evolving standard.
Still others may feel outdated, and yet still resonate today. This chapter
contains those items that just don't fit easy categories.
Item 45: Minimize Boxing and Unboxing
Va l u e t y p e s a r e c o n t a i n e r s f o r d a t a . T h e y a r e n o t p o l y m o r p h i c t y p e s . O n
the other hand, the .NET Framework was designed with a single reference
type, System.Object, at the root of the entire object hierarchy. These two
goals are at odds. The .NET Framework uses boxing and unboxing to
bridge the gap between these two goals. Boxing places a value type in an
untyped reference object to allow the value type to be used where a refer-
ence type is expected. Unboxing extracts a copy of that value type from
the box. Boxing and unboxing are necessary for you to use value types
where the System.Object type is expected. But boxing and unboxing are
always performance-robbing operations. Sometimes, when boxing and
unboxing also create temporary copies of objects, it can lead to subtle bugs
in your programs. Avoid boxing and unboxing when possible.
Boxing converts a value type to a reference type. A new reference object,
the box, is allocated on the heap, and a copy of the value type is stored
inside that reference object. See Figure 6.1 for an illustration of how the
boxed object is stored and accessed. The box contains the copy of the value
type object and duplicates the interfaces implemented by the boxed
value type. When you need to retrieve anything from the box, a copy of the
value type gets created and returned. That's the key concept of boxing and
unboxing: A copy of the value goes in the box, and another gets created
whenever you access what's in the box.
275
 
 
 
 
Search WWH ::




Custom Search