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,
Similar to Allon's answer, but should return the correct answer for any type without generating a compile-time error:
int i = 123;
Console.WriteLine(IsBoxed(i)); // false
object o = 123;
Console.WriteLine(IsBoxed(o)); // true
IComparable c = 123;
Console.WriteLine(IsBoxed(c)); // true
ValueType v = 123;
Console.WriteLine(IsBoxed(v)); // true
int? n1 = 123;
Console.WriteLine(IsBoxed(n1)); // false
int? n2 = null;
Console.WriteLine(IsBoxed(n2)); // false
string s1 = "foo";
Console.WriteLine(IsBoxed(s1)); // false
string s2 = null;
Console.WriteLine(IsBoxed(s2)); // false
// ...
public static bool IsBoxed(T item)
{
return (item != null) && (default(T) == null) && item.GetType().IsValueType;
}
public static bool IsBoxed(T? item) where T : struct
{
return false;
}
(Although you could make the argument that the possible compile-time error caused by Allon's code is a feature, not a bug: if you hit a compile-time error then you're definitely not dealing with an unboxed value type!)