Private Constructor


In this article we are going to discuss about private constructor with examples in C#.

Private Constructor

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.

Features of Private Constructors

  1. Accessibility - Private constructors can only be accessed within the class they are defined in.
  2. Preventing Instantiation - They prevent other classes from creating instances of the class.
  3. Singleton Pattern - Often used to implement the singleton design pattern, ensuring that only one instance of the class can exist.
  4. Static Classes - Can be used to create classes that only contain static members and prevent instantiation of the class.

Syntax

Here is the syntax for defining a private constructor.

class MyClass
{
    // Private constructor
    private MyClass()
    {
        // Initialization code
    }
}

Example - Singleton Pattern

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

Private Constructor in C#

Above Program Execution Steps

  1. Class Loading - When the program starts, the Program class is loaded. The Main method is identified as the entry point of the application.

  2. Static Member Access -The first time Singleton.Instance is accessed in Main, the Instance property of the Singleton class is invoked.

  3. Instance Check - Inside the Instance property, the program checks if the instance field is null.

    • First Access - Since this is the first access, instance is null.
    • Instance Creation - The private constructor Singleton() is called to create a new instance. This prevents any other class or code from instantiating the Singleton class directly.
    • Console Output - The message "Private constructor called." is printed to the console.
  4. Returning Instance - The newly created instance is assigned to the instance field and then returned by the Instance property.

  5. Method Invocation - The ShowMessage method is called on singleton1, which prints Singleton instance method called. to the console.

  6. Subsequent Access - When Singleton.Instance is accessed again, the Instance property is invoked.

    • Instance Check - This time, the instance field is not null because it already holds the previously created instance.
    • Returning Existing Instance - The existing instance is returned without calling the constructor again.
    • Method Invocation - The ShowMessage method is called on singleton2, printing Singleton instance method called. again

When to Use Private Constructors

  • Singleton Pattern - When you want to ensure a class has only one instance.
  • Static Utility Classes - When you want to create a class that only contains static methods and properties and should not be instantiated.
  • Factory Methods - When you want to control the instantiation process through factory methods or other patterns.

Prev Next