Search code examples
c#resharperabstract-class

What's wrong with bodyless abstract methods in abstract class?


I'm refactoring a pre-existing solution. I use ReSharper and I've noticed a code inspection rule is being tripped. There is an abstract class which has bodyless method signatures with the intention of forcing the derived classes (of which there are several). As far as my knowledge goes, this is the (or at least a) correct way to do things. However, ReSharper is complaining that the "Type member is never accessed via base type" and that "Only overrides of [the methods] are used." Here is example code that replicates the issue in question:

public abstract class MyAbstractClass
{
    public abstract void CreateSomething();
    public abstract void ReadSomething();
    public abstract void InsertSomething();
}

public class MyDerivedClass : MyAbstractClass
{

    public override void CreateSomething()
    {
        throw new NotImplementedException();
    }

    public override void ReadSomething()
    {
        throw new NotImplementedException();
    }

    public override void InsertSomething()
    {
        throw new NotImplementedException();
    }
}

By the way, there are other members that rule out making the abstract class an interface. ReSharper suggests making changes to the 3 methods in the abstract class. Its suggestions are to make them protected, virtual, non-abstract or to simply remove them from the abstract class and only have them in derived classes. Whoever originally wrote this code intended for every derived class to implement these methods, and for those methods to be public in the derived classes. So, is there some way I should change this to make it more effective? If not, why is ReSharper taking issue with this?


Solution

  • As mentioned by Rob in the comments, just use the abstract base class as type, while creating instances of the derived class in your code, e.g.

        MyAbstractClass myInstance = new MyDerivedClass(); // Polymorphism applied
        myInstance.CreateSomething();
        myInstance.InsertSomething();
        myInstance.ReadSomething();
    

    instead of creating new instances like this

        var myInstance = new MyDerivedClass(); // Polymorphism NOT applied
    

    or this

        MyDerivedClass myInstance = new MyDerivedClass(); // Polymorphism NOT applied
    

    to consider and solve the R# hint:

    ReSharper Hint

    By doing so, Polymorphism is applied correctly in the code, which was certainly the intention of the creators/maintainers of your pre-existing solution.