How to check if a generic type parameter is nullable?

13,325

You can use Nullable.GetUnderlyingType:

var t = typeof(T);
// ...
if (Nullable.GetUnderlyingType(t) != null)
{
    // T is a Nullable<>
}
Share:
13,325

Related videos on Youtube

Earlz
Author by

Earlz

Hello there! My name's Jordan Earls, but most people online know me as "earlz". I'm the lead developer and a co-founder of the Qtum project which brings the Ethereum Virtual Machine (ie, the thing that makes Solidity contracts function) to a UTXO based blockchain similar to Bitcoin. I've been programming since I was 13 and am completely self-taught. Low-level code like assembly and pointer arithmetic is the fun stuff for me. I also make music when I have time even though it's usually awful. Most of my personal projects are open source and BSD licensed. The majority of them are at bitbucket with the rest of them being listed on github Also, you can follow me on the twitters @earlzdotnet

Updated on June 22, 2020

Comments

  • Earlz
    Earlz almost 4 years

    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.

    • Nix
      Nix almost 13 years
    • Earlz
      Earlz almost 13 years
      @Nix that's in VB, so maybe borderline not a dupe. We'll see
    • Nix
      Nix almost 13 years
      The solutions are in C# and VB
  • niproblema
    niproblema over 3 years
    This is not working in my version of .NET Core 3.1 with C#8.0
  • JohnnyFun
    JohnnyFun over 2 years
    Works in net5.0/c#9, fwiw