Sometimes, you may have a scenario whereby you need to know if a value is a value type (say 'int'), or a nullable type (say 'int?').
Common sense suggests that we should easily be able to detect wether a type is nullable or not, but if you have a try, you'll see there are no obvious answers, or many unobvious ones either.
The problem stems from the fact that if you query the type of a nullable instance it'll cause it to be boxed, and the boxing operation means that GetType() brings back the type of the underlying valuetype - not the nullable.
However, after a bit of head-scratching, I ended up with this utility class
public static class ValueTypeHelper
{
public static bool IsNullable<T>(T t) { return false; }
public static bool IsNullable<T>(T? t) where T : struct { return true; }
}
and here's the test
static void Main(string[] args)
{
int a = 123;
int? b = null;
object c = new object();
object d = null;
int? e = 456;
var f = (int?)789;
bool result1 = ValueTypeHelper.IsNullable(a); // false
bool result2 = ValueTypeHelper.IsNullable(b); // true
bool result3 = ValueTypeHelper.IsNullable(c); // false
bool result4 = ValueTypeHelper.IsNullable(d); // false
bool result5 = ValueTypeHelper.IsNullable(e); // true
bool result6 = ValueTypeHelper.IsNullable(f); // true
}
Dean