S2955 — Generic parameters not constrained to reference types should not be compared to "null"

Language
C#
Type
Bug
Severity
Minor

Why is this an issue?

In C#, without constraints on a generic type parameter, both reference and value types can be passed. However, comparing this type parameter to null can be misleading as value types, like struct, can never be null.

How to fix it

To avoid unexpected comparisons:

Code examples

Noncompliant code example


bool IsDefault<T>(T value)
{
  if (value == null) // Noncompliant
  {
    // ...
  }
}

Compliant solution


bool IsDefault<T>(T value)
{
  if (EqualityComparer<T>.Default.Equals(value, default(T)))
  {
    // ...
  }
}

or


bool IsDefault<T>(T value) where T : class
{
  if (value == null)
  {
    // ...
  }
}

Resources

Documentation

↑ Back to top