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.
One way is to take advantage of the object-orientation of C# and use polymorphism.
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.
public class Food
{
public void DoSomething()
{
// Code shared by all Food...
if (this is Pizza) // Noncompliant
{
// Code specific to Pizza...
}
}
}
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...
}
}