Article Overview

Background

Here, I have described the private constructor and its usage in C#. This article will be useful to both beginners and professional C# developers.

What is a Private Constructor?

Can you create an object of class with a private constructor in C#?

What is the use of a private constructor in C#?

Practical Scenarios

Example 1

How does a private constructor stop object creation of a class?

public class Student {
    private Student() {
        // Private constructor prevents external instantiation
    }
    // You might want to add some public methods or fields here
}
public class MainClass {
    public static void main(String[] args) {
        // Attempting to create an instance of the Student class
        // This will result in a compilation error since the constructor is private
        // Student student = new Student();
        // If you want to use the Student class, you might need to modify its accessibility
    }
}

Output

It will give a compile time error like “'Student. Student()' is inaccessible due to its protection level”

Example 2

How does a private constructor stop object creation of a class?

public class Student {
    private Student() {
        // Private constructor prevents external instantiation
    }
    // You might want to add some public methods or fields here
}
public class Engineer extends Student {
    // You can add additional fields and methods specific to Engineer here
}

Output

It will give a compile time error like “'Student. Student()' is inaccessible due to its protection level”

Example 3

How does a private constructor stop object creation of a class?

using System;
public class SingletonDemo
{
    private static string CreatedOn;
    private static SingletonDemo instance = null;
    private static readonly object lockObject = new object(); // For thread safety
    private SingletonDemo()
    {
        CreatedOn = DateTime.Now.ToLongTimeString();
    }
    public static SingletonDemo GetInstance()
    {
        lock (lockObject) // Adding thread safety
        {
            if (instance == null)
            {
                instance = new SingletonDemo();
            }
        }
        Console.WriteLine(instance.CreatedOn); // Print the creation time
        return instance;
    }
}

Now, use the above class as follows.

class Program
{
    static void Main(string[] args)
    {
        SingletonDemo.GetInstance();
        System.Threading.Thread.Sleep(5000);
        SingletonDemo.GetInstance();
        System.Threading.Thread.Sleep(5000);
        SingletonDemo.GetInstance();
    }
}

Output

It will display the same time all the time as below. Hence, it will create an instance only once.

6:34:02 PM

6:34:02 PM

6:34:02 PM

Note. Here, for the basic understanding, I have not taken a thread-safe singleton example, but you can use thread-safe singleton in actual implementation.

Summary

Now, I believe you know the important key things about private constructors in C#.