What is Private constructor? What is the use? with code

A private constructor in C# is a constructor that is explicitly declared with the private access modifier. It restricts the accessibility of the constructor to the containing class itself. This means that objects of the class cannot be created using the new keyword from outside the class.

Here's an example to demonstrate a private constructor and its use:

csharp
public class Singleton { private static Singleton instance; // Private constructor private Singleton() { // Initialization code } public static Singleton GetInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

In this example, the Singleton class has a private constructor, meaning it can only be accessed within the class itself. The class also includes a GetInstance() method, which provides a way to obtain the instance of the Singleton class.

The primary use of a private constructor is to control object creation and ensure that only a single instance of the class is available. This is often used in the implementation of the Singleton design pattern, where only one instance of a class should exist throughout the application.

With a private constructor, you can restrict object creation to a specific method or within the class itself, giving you control over the creation and lifecycle of the object. In the example above, the private constructor ensures that the Singleton class cannot be instantiated directly, and the only way to obtain an instance is through the GetInstance() method, which ensures the creation of a single instance.

Here's how you can obtain the instance of the Singleton class:

csharp
Singleton instance = Singleton.GetInstance();

The use of a private constructor in combination with other mechanisms, such as static members or lazy initialization, allows you to enforce the creation of a single instance of a class, maintain global state, or manage access to limited resources.


 

Post a Comment

Previous Post Next Post