mardi 7 avril 2015

How to determine if a runtime object is of a nullable type

First: this is not a duplicate of How to check if an object is nullable?. Or, at least, there was no useful answer provided to that question, and the author's further elaboration actually asked how to determine whether a given type (eg. as returned from MethodInfo.ReturnType) is nullable.


However, that is easy. The hard thing is to determine whether a runtime object whose type is unknown at compile time is of a nullable type. Consider:



public void Foo(object obj)
{
var bar = IsNullable(obj);
}

private bool IsNullable(object obj)
{
var type = obj.GetType();
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
// Alternatively something like:
// return !(Nullable.GetUnderlyingType(type) != null);
}


This does not work as intended, because the GetType() call results in a boxing operation (http://ift.tt/1DfqSAH), and will return the underlying value type, rather than the nullable type. Thus IsNullable() will always return false.


Now, the following trick uses type parameter inference to get at the (unboxed) type:



private bool IsNullable<T>(T obj)
{
var type = typeof(T);
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}


This seems initially promising. However, type parameter inference only works when the type of the object is known at compile time. So:



public void Foo(object obj)
{
int? genericObj = 23;

var bar1 = IsNullable(genericObj); // Works
var bar2 = IsNullable(obj); // Doesn't work (type parameter is Object)
}


In conclusion: the general problem is not to determine whether a type is nullable, but to get at the type in the first place.


So, my challenge is: how to determine if a runtime object (the obj parameter in the above example) is nullable? Blow me away :)






Aucun commentaire:

Enregistrer un commentaire