C# Private Constructor or Sealed Class to stop inheritance?

(Last Updated On: March 6, 2017)

Interview Question: C# private constructor or sealed class, what to prefer to prevent class extension in inheritance and why?

Answer: Best choice is sealed class to prevent a 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.

 

Main purpose of a class having private constructor in C# programming is to stop object creation of the class. For example, we may want to create a utility class that contains methods only. So, 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 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#.