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.- public class Parent
- {
- private Parent()
- {
- }
-
- }
- public class Child : Parent
- {
-
- }
If we execute the above program, we will encounter the below error.
Let's create the object for a class.
- 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.