Skip to content


Getting encapsulated type of Nullable

Just a short tip for today..

Sometimes I’ve had the requirement to treat value types, where I don’t know if the value type is Nullable<T> or not. Regardless of whether the value type is declared as Nullable<T> or not, it should everytime be treat as T. Thus I’ve had to find out the underlying type of the Nullable<T>.

The following extension method on Type realizes this requirement:

public static class TypeExtensions
{
    public static Type GetBareType(this Type dataType)
    {
        if (dataType != null)
        {
            if (dataType.IsGenericType &&
               (dataType.GetGenericTypeDefinition() == typeof(Nullable<>)))
            {
                dataType = Nullable.GetUnderlyingType(dataType);
            }
        }
        return dataType;
    }
}

Posted in C#. Tagged with , , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.