What is the use of 'abstract override' in C#?

Manish Basantani picture Manish Basantani · Jan 18, 2012 · Viewed 21.3k times · Source

Just out of curiosity I tried overriding a abstract method in base class, and method the implementation abstract. As below:

public abstract class FirstAbstract
{
    public abstract void SomeMethod();
}

public abstract class SecondAbstract : FirstAbstract
{
    public abstract override void SomeMethod();
    //?? what sense does this make? no implementaion would anyway force the derived classes to implement abstract method?
}

Curious to know why C# compiler allows writing 'abstract override'. Isn't it redundant? Should be a compile time error to do something like this. Does it serve to some use-case?

Thanks for your interest.

Answer

BrokenGlass picture BrokenGlass · Jan 18, 2012

There's a useful example for this on Microsoft Docs - basically you can force a derived class to provide a new implementation for a method.

public class D
{
    public virtual void DoWork(int i)
    {
        // Original implementation.
    }
}

public abstract class E : D
{
    public abstract override void DoWork(int i);
}

public class F : E
{
    public override void DoWork(int i)
    {
        // New implementation.
    }
}

If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.