C# Design – Access Modifiers for Abstract Class Constructors

access-modifierscdesignnet

What access modifier should I use for my constructors in an abstract class, given that the class cannot be instantiated? It seems like the access modifier is superfluous and should be implicitly protected since it can only be used from within a derived class' constructor via base().

Best Answer

As you mentioned, your options are protected and private.

protected seems like a good default, but don't forget about the case where you don't want your sub classes to invoke a specific constructor. For example:

public abstract class AbstractBase
{
    private AbstractBase(int foo, double bar)
    {
        this.CalculatedProperty = someComplexCalculation(foor, bar);
    }

    protected AbstractBase(string XXX, string YYY, int foo, double bar)
        : this(foo, bar)
    {
        this.XXX = XXX;
        this.YYY = YYY;
    }

    protected AbstractBase(string XXX, int foo, double bar)
        : this(XXX, "There is no YYY.  There is only XXX.", foo, bar)
    {
    }

// *snip*

}

In this (overly simplified) example, we guarantee that the values for foo, bar, and XXX are always specified and that CalculatedProperty and XXX are always set.

The private constructor allows us to have shared construction logic without code duplication. And, because it's private, sub-classes can't accidentally partially construct themselves.