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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Casting expressions are utilized to convert one data type to another, such as transforming an integer into a string. This is especially crucial in strongly typed languages like C, C++, C#, Java, Python, and others.

However, there are instances where casting expressions are not needed. These include situations like:

  • casting a variable to its own type
  • casting a subclass to a parent class (in the case of polymorphism)
  • the programming language is capable of automatically converting the given type to another

These scenarios are considered unnecessary casting expressions. They can complicate the code and make it more difficult to understand, without offering any advantages.

As a result, it’s generally advised to avoid unnecessary casting expressions. Instead, rely on the language’s type system to ensure type safety and code clarity.

Exceptions

Issues are not raised against the default literal.

How to fix it

To fix your code remove the unnecessary casting expression.

Code examples

Noncompliant code example

public int Example(int i)
{
    return (int) (i + 42); // Noncompliant
}

public IEnumerable<int> ExampleCollection(IEnumerable<int> coll)
{
    return coll.Reverse().OfType<int>(); // Noncompliant
}

Compliant solution

public int Example(int i)
{
    return i + 42;
}

public IEnumerable<int> ExampleCollection(IEnumerable<int> coll)
{
    return coll.Reverse();
}
bool b = (bool)default; // Doesn't raise an issue

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy