tags:

views:

807

answers:

3

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.

+3  A: 

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.

BFree
Is there any way to make this very general purpose? How about a string that is null? Can I still get back a string?
Andrew Robinson
No. It won't work for the normal reference types. If you have nothing, you can't tell what it could be. That would be like me giving you an empty box then asking what colour the book is. It works for nullable types becuase they are a bit odd and have an object instance to represent null.
pipTheGeek
What happens when I pass in some other generic type? eg, List<DateTime>, Action<string, int> etc
LukeH
This method would work for any generic type, even List or Action. In the case of Action you asked however, it would just give you back the first argument "string".
BFree
A: 

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.

FailBoy
+1  A: 

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
Samuel