CSharp/C# Tutorial - C# Boxing and Unboxing






The object Type

object or System.Object is the ultimate base class for all types.

Any type can be upcast to object.

The following code creates a class Stack to provide a First-In-Last_Out data structure.

public class Stack {
    int position; 
    object[] data = new object[10];
    public void Push (object obj) { data[position++] = obj; }
    public object Pop() { return data[--position]; } 

} 

Because Stack works with the object type, we can Push and Pop any type to and from the Stack.

Stack stack = new Stack(); 
stack.Push ("CSS"); 
string s = (string) stack.Pop(); // Downcast, so explicit cast is needed 
Console.WriteLine (s);




Boxing and Unboxing

When casting between a value type and object, the CLR must perform the process of boxing and unboxing.

Boxing

Boxing is to convert a value-type instance to a reference-type instance.

The reference type may be either the object class or an interface.

int x = 1; 
object obj = x; // Box the int 

Unboxing

Unboxing reverses the operation, by casting the object back to the original value type:

int y = (int)obj; // Unbox the int 

Unboxing requires an explicit cast.

For instance, the following throws an exception, because long does not exactly match int:

object obj = 1; // 1 is inferred to be of type int 
long x = (long) obj; // InvalidCastException 

The following code does the unboxing and cast:

object obj = 9; 
long x = (int) obj;