SoFunction
Updated on 2025-03-06

Analyze whether abstract and override can be used at the same time

Can an attribute or method be modified by both abstract and override? A colleague of mine asked me this. My initial reaction was: "Of course not", but in fact it proved that it can be modified together.

I thought about this issue seriously. Although this method is rare, it is legal and even has some meaning.

Suppose we have a very large, complex type, let's call him "Thingy":

abstract class Thingy
{
  public virtual string Name { get { return ""; } }
}

Of course, Thingy will be integrated by many subclasses, and most subclasses have a default "" Name, or null,

Or something else. The key point is not what value this Name has, but for most classes in the type hierarchy

There is a meaningful default name.

However, if there is another abstract thingy, FrobThingy, it always has a non-empty name.

The subclass of FrobThingy unexpectedly calls the implementation of thingy, we can do this:

abstract class FrobThingy : Thingy
{
  public abstract override string Name { get; }
}

In this way, if you have a subclass BigFrobThingy, you have to provide the implementation of the Name property yourself, because if you don't provide it

If you do, you won't be able to compile.