C# Private Constructors: Controlling Object Instantiation and Class Usage

Learn how to use private constructors in C# to restrict object creation from outside a class. This tutorial explains their purpose, demonstrates their use in creating utility classes and implementing singleton patterns, and highlights how private constructors enhance class design and control object instantiation.



Understanding Private Constructors in C#

A private constructor in C# restricts the creation of instances (objects) of a class from outside that class. This is a powerful tool for controlling object creation and is often used for creating utility classes or singleton patterns.

Creating Objects with a Private Constructor

A class with only a private constructor cannot be instantiated directly from outside the class. However, you can create instances *within* the same class. This is demonstrated in the example below:


using System;

class MyClass {
    private MyClass() { Console.WriteLine("Private constructor called."); }
    public void MyMethod() { Console.WriteLine("MyMethod called."); }

    public static void Main(string[] args) {
        MyClass obj = new MyClass(); // Creating an instance *inside* the class
        obj.MyMethod(); // Calling a method
    }
}

Creating Instances from Outside the Class

To allow external instantiation, a class must have at least one public constructor. The presence or absence of a private constructor doesn't prevent the creation of objects using a public constructor.


public class MyClass {
    private MyClass() { } // Private constructor
    public MyClass(int x) { } // Public constructor
    public void MyMethod() { }
}

Private Constructor and Instantiation Errors

If a class has *only* a private constructor and no public constructors, attempting to create an instance from outside the class will result in a compiler error.

Using Private Constructors

A primary use case for private constructors is to prevent external instantiation, often used in singleton patterns or utility classes where only one instance of the class is needed, or where the class is intended only to be used internally within another class.

Private Constructors and Inheritance

A private constructor does *not* inherently prevent inheritance. A class with a private constructor can still be inherited as long as it also has at least one public constructor. The child class will use the public constructor of the parent class during the inheritance process.


public class Parent {
    private Parent() { } // Private constructor
    public Parent(string message) { Console.WriteLine(message); }
}

public class Child : Parent {
    public Child() : base("Hello from Parent!") { Console.WriteLine("Child created"); }
}