What is the difference between boxing/unboxing and type casting?
Often, the terms seem to be used interchangeably.
.netboxingcastingunboxing
What is the difference between boxing/unboxing and type casting?
Often, the terms seem to be used interchangeably.
Best 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
toIComparable<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,
converts
i
to an instance of typeobject
.Unboxing refers to an explicit conversion from an instance of
object
orValueType
to a non-nullable-value type, the conversion of an interface type to a non-nullable-value type (e.g.,IComparable<int>
toint
). 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,
converts the integer boxed in
o
to an instance of typeint
.A type cast is an explicit conversion of an expression to a given type. Thus
explicitly converts
expression
to an object of typetype
.