C#

C#

By DeepSource

Comparing an entity's type against typeof(Nullable<T>) is unreliable CS-W1069

Bug risk

The GetType() method returns System.Type that can be compared against typeof expression. However, invoking the GetType() method on a nullable entity always returns the underlying type. Therefore, comparing it with typeof(Nullable<T>) or typeof(T?) will evaluate to false. Consider replacing Nullable<T> or T? with just T for reliable evaluation.

Examples

Bad Practice

// Using `Nullable<T>` in a `typeof()` expression
if (obj.GetType() == typeof(Nullable<T>))
{
    // ...
}

// Using `T?` in a `typeof()` expression
if (obj.GetType() == typeof(T?))
{
    // ...
}

Recommended

// Both the above snippets can be rewritten as:
if (obj.GetType() == typeof(T)
{
    // ...
}