Boxing and Unboxing

Boxing and Unboxing

Are you moving? Need a rental truck?  Oh, you’re talking about “Boxing” as in converting value types to reference types.

An example of boxing:

'Implicit boxing VB
Dim x as Int16 = 5
Dim obj as Object = x

//Implicit boxing C#
Int16 x = 5;
object obj = x;

'Explicit boxing VB
Dim x as Int16 = 5
Dim obj as Object = Ctype(x, Int16)

//Explicit boxing C#
Int16 x = 5;
object obj = (object) x;

Unboxing, as the name implies, is the exact opposite of boxing.

An example of unboxing:
Int16 x = 5; object obj = x; // implicit boxing x = (int) obj; // explicit unboxing

While boxing may not be a common term, or at least one that is thrown around much, most developers are boxing and unboxing without knowing they are doing so.