Using Abstract Override in C#

October 28th 2013 C#

Recently the following language construct has been brought to my attention:

public abstract override string ToString();

Knowing about both keywords used in the above example, there isn't much doubt what it means to the compiler:

  • Abstract methods don't have any implementation and require non-abstract derived classes to implement them. Of course they are allowed only in abstract classes.
  • Override allows a method to override a virtual or abstract method from its base class.

This means that the combination of both can be used in the following two cases:

  • In a class deriving from an abstract base class to override an abstract method and mark it as abstract. In this case the construct is completely redundant. The behavior would be the same if the abstract method from the base class wouldn't be overridden at all: it would still have to be overridden in any non-abstract derived class. Its presence does acknowledge the programmer's awareness of the abstract method in the base class and the intent not to implement it, but does nothing else. The construct is not even present in the compiled assembly.
  • In a class deriving from any base class to override a virtual method and break its inheritance chain. In this case the class deriving from this intermediate class will have to override the method even though it has an implementation in the original base class. This construct will prevent the derived class from accessing it and force it to come up with its own implementation. The introductory sample comes from such a scenario:
public abstract class BaseClass
{
    // remember that each class inherits from Object
    // which implements virtual ToString() method
    public abstract override string ToString();
}

public class DerivedClass : BaseClass
{
    // BaseClass forces DerivedClass to implement ToString()
    public override string ToString()
    {
        // base.ToString() doesn't compile
        // since method is not implemented in BaseClass
        // DerivedClass MUST come up with its own implementation
        return String.Empty;
    }
}

When would doing this be a good idea? I'm not really sure, and I couldn't come up with a really good example. Still, it's good to know that it can be done in C# and the CLR.

Copyright
Creative Commons License