Finding a more elegant way to check nullable type values

To check if the value type is null, I am doing something like this now:

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

Is there a more elegant way to do this?

+4
source share
3 answers

You can use Nullable.GetUnderlyingType(Type) - which will return null if it is not a type with a zero value to start with or enter a base value differently:

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

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

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

Here's how Microsoft recommends you Define Null Types

+7
source
 int? i; bool isNullable = i is Nullable; 

Edit : Nevermind, this does not work.

0
source

Source: https://habr.com/ru/post/1315105/


All Articles