0
0
CsharpConceptBeginner · 3 min read

What is Private Constructor in C# and How It Works

A private constructor in C# is a constructor that can only be called within the class itself. It prevents other classes from creating instances directly, often used to control object creation or implement patterns like singletons.
⚙️

How It Works

A private constructor is a special method inside a class that creates objects but is hidden from outside code. Imagine a factory where only the owner can make products, and customers can only get products the owner allows. This means no one outside the class can create new objects directly.

This is useful when you want to control how many objects exist or when you want to provide only specific ways to get an object, like a single shared instance. The class itself can still create objects inside its own code, but others cannot.

💻

Example

This example shows a class with a private constructor and a public method to get the single instance (singleton pattern).

csharp
using System;

public class Singleton
{
    private static Singleton _instance;

    // Private constructor prevents direct instantiation
    private Singleton()
    {
        Console.WriteLine("Singleton instance created.");
    }

    // Public method to get the single instance
    public static Singleton GetInstance()
    {
        if (_instance == null)
        {
            _instance = new Singleton();
        }
        return _instance;
    }
}

class Program
{
    static void Main()
    {
        // Cannot do: var s = new Singleton(); // Error

        var first = Singleton.GetInstance();
        var second = Singleton.GetInstance();

        Console.WriteLine(object.ReferenceEquals(first, second));
    }
}
Output
Singleton instance created. True
🎯

When to Use

Use a private constructor when you want to control how objects of a class are created. Common cases include:

  • Implementing the singleton pattern to ensure only one instance exists.
  • Creating utility or helper classes that only have static methods and should not be instantiated.
  • Controlling object creation through factory methods inside the class.

It helps keep your code safe and predictable by preventing unwanted or accidental creation of objects.

Key Points

  • A private constructor cannot be called from outside the class.
  • It is used to restrict object creation.
  • Commonly used in singleton and static utility classes.
  • The class itself can still create instances internally.

Key Takeaways

A private constructor restricts object creation to within the class only.
It is essential for implementing singletons and controlling instantiation.
Outside code cannot create instances directly when the constructor is private.
Use private constructors to enforce design patterns and improve code safety.