CSharp examples for Custom Type:Box Unbox
The reference type may be either the object class or an interface.
In this example, we box an int into an object:
int x = 9;
object obj = x; // Box the int
Console.WriteLine(x);
Console.WriteLine(obj);
Unboxing is casting the object back to the original value type:
int y = (int)obj; // Unbox the int
Unboxing requires an explicit cast.
The runtime checks that the stated value type matches the actual object type and throws an InvalidCastException if the check fails.
For instance, the following throws an exception, because long does not exactly match int:
object obj = 9; // 9 is inferred to be of type int long x = (long) obj; // InvalidCastException Console.WriteLine(x);
The following succeeds:
object obj = 9; long x = (int) obj; Console.WriteLine(x);
The following succeeds as well: (double) performs an unboxing, and then (int) performs a numeric conversion.
object obj = 3.5; // 3.5 is inferred to be of type double int x = (int) (double) obj; // x is now 3 Console.WriteLine(x);