Why should constructors on abstract classes be protected, not public?

C#.NetOopInheritanceAccess Modifiers

C# Problem Overview


ReSharper suggests changing the accessibility of a public constructor in an abstract class to protected, but it does not state the rationale behind this.

Can you shed some light?

C# Solutions


Solution 1 - C#

Simply because being public makes no sense in an abstract class. An abstract class by definition cannot be instantiated directly. It can only be instantiated by an instance of a derived type. Therefore the only types that should have access to a constructor are its derived types and hence protected makes much more sense than public. It more accurately describes the accessibility.

Solution 2 - C#

It technically makes no difference whatsoever if you make the constructor public instead of protected on an abstract class. The accessibility/visibility of the constructor is still exactly the same: the same class or derived classes. The two keywords have indistinguishable effects for all intents and purposes.

So, this choice is only a matter of style: type protected to satisfy the Object Oriented savvy people.


Reflection will by default only include the constructor when it is public, but you cannot call that constructor anyway.

IntelliSense will show the public constructor when typing new, but you cannot call that constructor anyway.

The assembly's metadata will reflect the fact that the constructor is public or protected.

Solution 3 - C#

It is good OO practice.

public abstract class ExampleAbstractClass
{
    protected ExampleAbstractClass()
    {
      // :::
    }
}

You only want the inheriting child classes to have access to the constructor. The only way to do that is by making the constructor protected.
Keep in mind, when you add parameters to these constructors, it is an entirely different discussion.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCristian DiaconescuView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#Daniel A.A. PelsmaekerView Answer on Stackoverflow
Solution 3 - C#Srikar DoddiView Answer on Stackoverflow