The concepts of boxing and unboxing are interesting ones.
They're associated with value and reference types. Boxing is the process
through which a programming language stores a value type as a reference type.
You might be wondering how this is different from the Nullable type discussed
in the section before this one.
Nullable is a special class which use generics to
have a value type they manage, and this is how they give the illusion of a
nullable value. When you use boxing, it is not using generics in such a nice
When you use boxing, the fact that your variable is a value
type is lost as the variable is stored as an object. A good way to remember
this term is that boxing is hiding your value inside of a box so you no longer
know what type of value it is. The following lines of code show an example of
Listing 3: Boxing and Unboxing
int myValue = 7; // Value type
object myObject = myValue; // Implicitly boxing the value
object myObject2 = (object)myValue; // Explicitly boxing the value
int theValueAgain = (int)myObject; // Explicitly unboxing the value
As you can see in this example, boxing and unboxing is easy
to do and happens often. If ever a value type is converted to object (which is
a reference type) boxing must occur. When you extract the value type back out
of that object you are unboxing the value.
An easy way to remember these terms is that when you put
something in a box you no longer see what it is, you just see the box. When you
pull something out of a box, you see what it really is since it is no longer
hidden away in the box.