Reputation: 22578
I am using reflection to get the values out of an anonymous type:
object value = property.GetValue(item, null);
when the underlying value is a nullable type (T?), how can I get the underlying type when the value is null?
Given
int? i = null;
type = FunctionX(i);
type == typeof(int); // true
Looking for FunctionX(). Hope this makes sense. Thanks.
Upvotes: 3
Views: 3884
Reputation: 103770
You can do something like this:
if(type.IsgenericType)
{
Type genericType = type.GetGenericArguments()[0];
}
EDIT: For general purpose use:
public Type GetTypeOrUnderlyingType(object o)
{
Type type = o.GetType();
if(!type.IsGenericType){return type;}
return type.GetGenericArguments()[0];
}
usage:
int? i = null;
type = GetTypeOrUnderlyingType(i);
type == typeof(int); //true
This will work for any generic type, not just Nullable.
Upvotes: 6
Reputation: 38366
If you know that is Nullable<T>
, you can use the static helper GetUnderlyingType(Type)
in Nullable
.
int? i = null;
type = Nullable.GetUnderlyingType(i.GetType());
type == typeof(int); // true
Upvotes: 2
Reputation: 17502
from what I understand on http://blogs.msdn.com/haibo_luo/archive/2005/08/23/455241.aspx you will just get a Nullable version of the type returned.
Upvotes: 0