C# Reflection: How to get the type of a Nullable<int>?

Zachary Scott picture Zachary Scott · Dec 18, 2011 · Viewed 26.5k times · Source

What I want to do is something like this:

switch( myObject.GetType().GetProperty( "id") )
{
    case ??: 
        // when Nullable<Int32>, do this
    case ??:
        // when string, do this
    case ??:
        // when Nullable<bool>, do this

What path under object.GetType() would have the string name of the datatype that I could compare using a case statement? I need to know the type so I can have one of many Convert.ToInt32( string ) that will set the value of myObject using Reflection.

Answer

Toni Parviainen picture Toni Parviainen · Dec 18, 2011

I've been using the following type of code to check if the type is nullable and to get the actual type:

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
    return Nullable.GetUnderlyingType(type);
}

If the type is e.g. Nullable this code returns the int part (underlying type). If you just need to convert object into specific type you could use System.Convert.ChangeType method.