What is private constructor in C#?
In C#, a private constructor is a constructor method that can only be accessed from within the class in which it is defined. This means that no other code outside the class can create an instance of the class using the private constructor.
Private constructors are typically used in situations where you want to prevent the creation of instances of a class from outside the class itself. For example, you might use a private constructor in a class that provides only static methods and properties, and should not be instantiated.
Here is an example of a class with a private constructor:
public class clsSingleton
{
private static Singleton instance;
private clsSingleton() // private constructor
{
// initialization code
}
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new clsSingleton();
}
return instance;
}
}
In this example, the constructor of the "clsSingleton" class is private, so it cannot be called from outside the class. Instead, the class provides a public static method called "GetInstance()" that returns a single instance of the class. This method checks if the instance has already been created, and if not, it creates it using the private constructor.
By making the constructor private, the "clsSingleton" class ensures that only one instance of the class can be created and that it can only be created from within the class itself. This is a common pattern used to enforce the singleton design pattern in C#.
No comments:
Post a Comment
If you have any query kindly let me know.