C# Private Constructor or Sealed Class to stop inheritance?

Interview Question: In C# private constructor or sealed class, which one would you prefer to prevent a class extension in inheritance and why?

Answer:

The best choice is using a sealed class to prevent the class not to be extended/inherited. This is true that private constructor and sealed class both can prevent extension of a class, means, we cannot derived any class from it. However, they have their own purpose and properties.

Read the below code and comments where extension of a class fails in both case i.e. a class having private constructor and a sealed class.

//-----------Private Constructor class: PC---------------
//Class having private constructor
class PC{
    private PC(){}
}

//Cannot extend PC class
//compile time error: PC.PC() is inaccessible
//due to its protection level
class PCDerived : PC
{
}

//-----------Sealed class: SC---------------
sealed class SC
{
    SC() { }
}
//Cannot extend Sealed class
//Compiler Error: SCDerived: cannot derive from sealed type SC
class SCDerived : SC
{
}

Main purpose of private constructor and sealed class.

The main purpose of a class having private constructor in C# programming is to stop object creation of the class outside of it. For example,

we may want to create a utility class that contains methods only. So, we can have only static methods in the class and call them using class name only. No need to create class object here. So, make the constructor private to prevent object creation.

And the main purpose of the sealed class is to prevent a class to be inherited/Extended.

Read here for Real time example of Sealed class and method in C#

Conclusion:

  • Use private constructor if we need to stop object creation of a class. Note that object can be created of a sealed class.
  • To stop extension of a class (independent class, base class or derived class) use sealed class in C#.

Related Posts