In this article we are going to discuss about private constructor with examples in C#.
In C#, a private constructor is a special type of constructor that is used to restrict the instantiation of a class. When a class has a private constructor, it cannot be instantiated from outside the class. Private constructors are useful in scenarios like implementing singleton patterns, creating static classes, or defining classes that only contain static members.
Here is the syntax for defining a private constructor.
class MyClass
{
// Private constructor
private MyClass()
{
// Initialization code
}
}
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. Consider the following example that demonstrates a private constructor in a singleton pattern.
using System;
class Singleton
{
// Private static instance of the same class
private static Singleton instance = null;
// Private constructor to prevent instantiation
private Singleton()
{
Console.WriteLine("Private constructor called.");
}
// Public static method to provide access to the instance
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
public void ShowMessage()
{
Console.WriteLine("Singleton instance method called.");
}
}
class Program
{
static void Main(string[] args)
{
// Trying to create an instance directly will result in a compile-time error
// Singleton obj = new Singleton(); // Error
// Accessing the instance through the public static method
Singleton singleton1 = Singleton.Instance;
singleton1.ShowMessage();
// Accessing the instance again to demonstrate it is the same instance
Singleton singleton2 = Singleton.Instance;
singleton2.ShowMessage();
}
}
Output
Class Loading - When the program starts, the Program class is loaded. The Main method is identified as the entry point of the application.
Static Member Access -The first time Singleton.Instance is accessed in Main, the Instance property of the Singleton class is invoked.
Instance Check - Inside the Instance property, the program checks if the instance field is null.
Returning Instance - The newly created instance is assigned to the instance field and then returned by the Instance property.
Method Invocation - The ShowMessage method is called on singleton1, which prints Singleton instance method called. to the console.
Subsequent Access - When Singleton.Instance is accessed again, the Instance property is invoked.