All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S2955.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

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:

  • if you expect a value type, use default() for comparison
  • if you expect a reference type, add a constraint to prevent value types from being passed

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





© 2015 - 2024 Weber Informatics LLC | Privacy Policy