Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a generic type parameter is nullable? [duplicate]

Tags:

Possible Duplicate:
Determine if a generic param is a Nullable type

I'm trying to determine if a type parameter is Nullable.

    public T Get<T>(int index)
    {
        var none=default(T);
        var t = typeof(T);
        BaseVariable v = this[index].Var;
        if (T is Nullable) //compiler error
        {
            if (v == ... )
            {
                return none;
            }
        }
        //....
    }

How do I do this? I've tried doing t == typeof(Nullable) but that always resulted in false.

What I want to happen is for foo.Get<bool?>(1) to null at times.

like image 953
Earlz Avatar asked Jun 21 '11 16:06

Earlz


1 Answers

You can use Nullable.GetUnderlyingType:

var t = typeof(T);
// ...
if (Nullable.GetUnderlyingType(t) != null)
{
    // T is a Nullable<>
}
like image 167
LukeH Avatar answered Oct 28 '22 23:10

LukeH