Importance & Use of the Private Constructor in C#

Introduction

 
In this blog, we are discussing the Importance and use of private constructors in C#. Generally, with most of the interviews, we have one common question, that is 'what is the use of the private constructor in C#? Let's discuss more about this.
  • A class with a private constructor cannot be inherited.
  • We cannot create an object of the class which has a private constructor. 
Let's understand the above points programmatically.
  1. public class Parent  
  2. {  
  3.    private Parent()  
  4.    {  
  5.    }  
  6.   
  7. }  
  8. public class Child : Parent  
  9. {  
  10.   
  11. }  
If we execute the above program, we will encounter the below error.
 
 
Let's create the object for a class.
  1. Parent obj = new Parent();  
If we execute the program, we will encounter the same error.
 
So now the next question from the interviewer is what is the use of such a class which cannot be inherited? In such a case, we can say the private constructor when we do not want to create an object or certain classes, for example, helper class. 
  
 

Summary

 
In this blog, we discussed the private constructor usage with examples.