How to check if a generic type parameter is nullable?
You can use Nullable.GetUnderlyingType
:
var t = typeof(T);
// ...
if (Nullable.GetUnderlyingType(t) != null)
{
// T is a Nullable<>
}
Related videos on Youtube
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, 2020Comments
-
Earlz almost 4 years
Possible Duplicate:
Determine if a generic param is a Nullable typeI'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 almost 13 yearsThis is a dup stackoverflow.com/questions/5181494/…
-
Earlz almost 13 years@Nix that's in VB, so maybe borderline not a dupe. We'll see
-
Nix almost 13 yearsThe solutions are in C# and VB
-
-
niproblema over 3 yearsThis is not working in my version of .NET Core 3.1 with C#8.0
-
JohnnyFun over 2 yearsWorks in net5.0/c#9, fwiw