Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to check if a type is Nullable [duplicate]

People also ask

How do you check if something is nullable?

GetUnderlyingType() != null to identity if a type is nullable.

Which statement is true about nullable type?

Characteristics of Nullable TypesNullable types can only be used with value types. The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value. The HasValue property returns true if the variable contains a value, or false if it is null. You can only use == and !=

How can you check a nullable variable for any type of value in C#?

How to access the value of Nullable type variables? You cannot directly access the value of the Nullable type. You have to use GetValueOrDefault() method to get an original assigned value if it is not null. You will get the default value if it is null.

What is nullable type in C sharp?

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values. For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable.


Absolutely - use Nullable.GetUnderlyingType:

if (Nullable.GetUnderlyingType(propertyType) != null)
{
    // It's nullable
}

Note that this uses the non-generic static class System.Nullable rather than the generic struct Nullable<T>.

Also note that that will check whether it represents a specific (closed) nullable value type... it won't work if you use it on a generic type, e.g.

public class Foo<T> where T : struct
{
    public Nullable<T> Bar { get; set; }
}

Type propertyType = typeof(Foo<>).GetProperty("Bar").PropertyType;
// propertyType is an *open* type...

Use the following code to determine whether a Type object represents a Nullable type. Remember that this code always returns false if the Type object was returned from a call to GetType.

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}

explained at the below MSDN link:

http://msdn.microsoft.com/en-us/library/ms366789.aspx

Moreover, there is a similar discussion at this SO QA:

How to check if an object is nullable?