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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

In C#, the is type testing operator can be used to check if the run-time type of an object is compatible with a given type. If the object is not null, then the is operator performs a cast, and so performing another cast following the check result is redundant.

This can impact:

  • Performance: Performing the type check and cast separately can lead to minor performance issues. While this might not be noticeable in small applications, it can add up in larger, more complex systems.
  • Readability: The code is less readable and less clean because it requires two lines (and two operations) to achieve something that could be done in one.

How to fix it

Use pattern macthing to perform the check and retrieve the cast result.

Code examples

Noncompliant code example

if (x is Fruit)  // Noncompliant
{
  var f = (Fruit)x; // or x as Fruit
  // ...
}

Compliant solution

if (x is Fruit fruit)
{
  // ...
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy