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

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

There is a newer version: 9.30.0.95878
Show newest version

Why is this an issue?

One of the possible ways of performing type-testing is via the is operator: food is Pizza.

The is operator is often used before a direct cast to the target type, as a more flexible and powerful alternative to the as operator, especially when used to perform pattern matching.

if (food is Pizza pizza)

There’s no valid reason to test this with is. The only plausible explanation for such a test is that you’re executing code in a parent class conditionally based on the kind of child class this is.

public class Food
{
  public void DoSomething()
  {
    if (this is Pizza) // Noncompliant
    {
      // Code specific to Pizza...
    }
  }
}

However, code that’s specific to a child class should be in that child class, not in the parent.

How to fix it

One way is to take advantage of the object-orientation of C# and use polymorphism.

  • Make the method virtual, if it is not already. That will allow derived classes to perform method overriding.
  • Move the code to the right level of the type hierarchy.
  • Use base to call the method on the base class that has been overridden.

For example, when simple method polymorphism is not enough because it is necessary to reuse multiple sections of the parent method, the Template method pattern might help.

Code examples

Noncompliant code example

public class Food
{
  public void DoSomething()
  {
    // Code shared by all Food...
    if (this is Pizza) // Noncompliant
    {
      // Code specific to Pizza...
    }
  }
}

Compliant solution

public class Food
{
  public virtual void DoSomething()
  {
    // Code shared by all Food...
  }
}

public class Pizza : Food
{
  public override void DoSomething()
  {
    base.DoSomething();
    // Code specific to Pizza...
  }
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy