What is Use of Private Constructor in C# ? Scenarios Example

(Last Updated On: January 18, 2018)

Answer to interview questions, what is use of private constructor in c# language includes definition of it and when or why to use private constructors in c sharp  application with c# program example.

Private Constructor in C#?

Private constructor is constructor that is preceded by private access specifier. For example, below class has a private constructor.

We know that if we don’t write constructor in the class then by default constructor gets called on object creation which is public. Or if we want to allow object creation of the class then we write public constructor or else we explicitly specify private access specifier on class constructor.

Can we create object of class with private constructor in C#?

No, object of a class having private constructor cannot be instantiated from outside of the class. However, we can create object of the class inside class methods itself.

 

 

Use of private constructor in C# Sharp Programming:

Following are the scenarios when we can make use of private constructor in C# code.

1)Stop object creation of a class

If we want to stop object creation of a class, then we can make the class constructor private. So, if we try to create an object from the main program or other classes, then compiler will flash an error.

2)Use in Singleton class

We know that singleton class allows only single instance of it throughout the execution of the application. When we design a singleton class, we use private constructor, so, no user can create object of this class to stop multiple object creation. And singleton class itself provide the same object over and over on demand.

NOTE
You may like reading what is singleton class and how to design thread safe singleton class in C# software projects.
3)Stop a class to be inherited

If we don’t want a class to be inherited, then we make the class constructor private. So, if we try to derive another class from this class then compiler will flash an error. Why compiler will flash an error? We know the order of execution of constructor in inheritance that when we create an object of a derived class then first constructor of the base call will be called then constructor of derived class. Since, base class constructor is private, hence, derived class will fail to access base class constructor.

In below c sharp code example, compiler flashes error on creation of object of derived class or as soon as you write constructor of derived class.

 

NOTE
We can also use sealed class to stop a class to be inherited. Sealed class provide more flexible and readable way to stop inheritance. Read the real-time example of sealed class and another example of Use of sealed class in C# projects.