I\'m looking for a way to write code that tests whether a value is boxed.
My preliminary investigations indicate that .NET goes out of its way to conceal the fact,
GetType() and IsValueType don't reveal the difference between a boxed value and an unboxed value.
GetType is a sealed (non-virtual) method on System.Object
. Calling this method on a value-type will definitely box it. Not even Nullable
is able to get around this - calling GetType
on a nullable will return the underlying type if it has a value (boxed as the underlying type) or throw a NullReferenceException
if it doesn't (boxed to null, can't dereference a null-reference).
when looking at any variable or value, even if its type is "dynamic" or "object," whether it's boxed or not boxed.
In general, if you have an expression that "holds" a value-type, the value of that expression will be a reference to a box unless the expression's compile-time type is of the value-type itself (generics are slightly more complicated). Common reference-types that can hold references to boxed structures are object
, dynamic
and interface-types.