«^»
5.5. Boxing and unboxing

As mentioned previously, the value types are struct types and enumeration types, where the struct types include the predefined simple types. When appropriate, an object is automatically created from a variable that is of some value type. This is known as boxing.

For example:

int tStudentNumber = 123;
object tStudentBox = tStudentNumber;

results in:

Boxing is a two-stage process: create an object and then copy the value of the variable into the object.

Unboxing is achieved as follows:

int tStudentNumberAgain = (int) tStudentBox;

An InvalidCastException exception is thrown if you attempt to cast to an inappropriate type.

Automatic boxing and unboxing are not present in Java. Instead, in Java, you have to do these tasks explicitly using the wrapper types, e.g.:

int tStudentNumber = 123;
Object tStudentBox = new Integer(tStudentNumber);
int tStudentNumberAgain = ((Integer)tStudentBox).intValue();

Microsoft's marketing refers to C#'s unified type system. The phrase Everything is an object is used: this means that, because boxing and unboxing are automatically performed, everything can be treated as an object even if it is a value of a value type.

Here is a more convincing example. Like Java, C# has a collection class called ArrayList. This class has a method called Add which is declared as:

public int Add(object pObject);

So, like Java, we can do:

ArrayList tArrayList = new Arraylist();
tArrayList.Add("Hello world");
Date tDate = new Date(2001, 3, 13);
tArrayList.Add(tDate);

However, in C#, we can also do:

int tStudentNumber = 123;
tArrayList.Add(tStudentNumber);

In Java, you would have to write:

int tStudentNumber = 123;
tArrayList.add(new Integer(tStudentNumber));