Boxing and unboxing are important concepts in C#, allowing you to convert .NET data types from a value type to a reference type, and visa versa.
There are three data types in C#:
- Value types - These include types such as int, char, and bool. A variable of a value type contains an instance of the type.
- Reference types - These include types such as strings, arrays, and objects. A variable of a reference type contains a reference to the instance of the type.
- Pointer types - A variable that holds the memory address of another type.
What is Boxing?
Boxing allows us to convert a value type, into a reference type:
class BoxingUnboxing
{
static void Main()
{
int myVal = 1;
object obj = myVal; // Boxing
}
}
Since we were able to assign directly to object without any special syntax, the conversion is implicit.
What is Unboxing?
Unboxing however, allows us to convert a reference type back into a value type:
class BoxingUnboxing
{
static void Main()
{
int myVal = 1;
object obj = myVal; // Boxing
int newVal = (int)obj; // Unboxing
}
}
Unlike the boxing example, we needed to cast the object back using (int) before assigning it. This conversion is explicit.