Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for a more elegant way to check for nullable value types

To check if a value type is nullable I'm currently doing something like this:

int? i = null;
bool isNullable = i.GetType().ToString().Contains("System.Nullable");

Is there a more elegant way to do this?

like image 699
RobSullivan Avatar asked Nov 29 '22 18:11

RobSullivan


2 Answers

You can use Nullable.GetUnderlyingType(Type) - that will return null if it's not a nullable type to start with, or the underlying value type otherwise:

if (Nullable.GetUnderlyingType(t) != null)
{
    // Yup, t is a nullable value type
}

Note that this uses the Nullable static class, rather than the Nullable<T> structure.

like image 73
Jon Skeet Avatar answered Dec 10 '22 04:12

Jon Skeet


if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
  // it is a nullable type
}

This is how Microsoft recommends you Identify Nullable Types

like image 34
Iain Ward Avatar answered Dec 10 '22 05:12

Iain Ward