What is the difference between boxing/unboxing and type casting?

.net, boxing, casting, unboxing

Solution

Boxing refers to a conversion of a non-nullable-value type into a reference type or the conversion of a value type to some interface that it implements (say `int` to `IComparable<int>`). Further, the conversion of an underlying value type to a nullable type is also a boxing conversion. (Caveat: Most discussions of this subject will ignore the latter two types of conversions.)

For example,

int i = 5;
object o = i;

converts `i` to an instance of type `object`.

Unboxing refers to an explicit conversion from an instance of `object` or `ValueType` to a non-nullable-value type, the conversion of an interface type to a non-nullable-value type (e.g., `IComparable<int>` to `int`). Further, the conversion of a nullable type to the underlying type is also an unboxing conversion. (Caveat: Most discussion of this subject will ignore the latter two types of conversions.)

For example,

object o = (int)5;
int i = (int)o;

converts the integer boxed in `o` to an instance of type `int`.

A type cast is an explicit conversion of an expression to a given type. Thus

(type) expression

explicitly converts `expression` to an object of type `type`.

Problem

What is the difference between boxing/unboxing and type casting? Often, the terms seem to be used interchangeably.

Original source

Related problems