Search code examples
c#language-designabstract

Why does C# allow for an abstract class with no abstract members?


The C# spec, section 10.1.1.1, states:

An abstract class is permitted (but not required) to contain abstract members.

This allows me to create classes like this:

public abstract class A
{
    public void Main() 
    {
        // it's full of logic!
    }
}

Or even better:

public abstract class A
{
    public virtual void Main() { }
}

public abstract class B : A
{
    public override sealed void Main()
    {
        // it's full of logic!
    }
}

This is really a concrete class; it's only abstract in so far as one can't instantiate it. For example, if I wanted to execute the logic in B.Main() I would have to first get an instance of B, which is impossible.

If inheritors don't actually have to provide implementation, then why call it abstract?

Put another way, why does C# allow an abstract class with only concrete members?

I should mention that I am already familiar with the intended functionality of abstract types and members.


Solution

  • Perhaps a good example is a common base class that provides shared properties and perhaps other members for derived classes, but does not represent a concrete object. For example:

    public abstract class Pet
    {
        public string Name{get;set;}
    }
    
    public class Dog : Pet
    {
        public void Bark(){ ... }
    }
    

    All pets have names, but a pet itself is an abstract concept. An instance of a pet must be a dog or some other kind of animal.

    The difference here is that instead of providing a method that should be overridden by implementors, the base class declares that all pets are composed of at least a Name property.