A class with only abstract methods and no inheritable behavior should be converted to an interface.
The purpose of an abstract
class is to provide some overridable behaviors while also defining methods that are required to be implemented by sub-classes.
A class that contains only abstract methods, often called pure abstract class, is effectively an interface, but with the disadvantage
of not being able to be implemented by multiple classes.
Using interfaces over pure abstract classes presents multiple advantages:
abstract classes that contain non-abstract methods, in addition to abstract ones, cannot easily be converted to
interfaces, and are not the subject of this rule:
public abstract class Lamp // Compliant: Glow is abstract, but FlipSwitch is not
{
private bool switchLamp = false;
public abstract void Glow();
public void FlipSwitch()
{
switchLamp = !switchLamp;
if (switchLamp)
{
Glow();
}
}
}
Notice that, since C# 8.0, you can also define default implementations for interface methods, which is yet another reason to prefer interfaces over abstract classes when you don’t need to provide any inheritable behavior.
However, interfaces cannot have fields (such as switchLamp in the example above), and that remains true even in C# 8.0 and upwards.
This can be a valid reason to still prefer an abstract class over an interface.
Convert the abstract class to an interface with the same methods.
public abstract class Animal // Noncompliant: should be an interface
{
public abstract void Move();
public abstract void Feed();
}
public interface Animal
{
void Move();
void Feed();
}