C# Private Constructor (with example)

A Private Constructor is an instance constructor used to prevent creating an instance of a class if it has no instance fields or methods. It is used in classes that contain only static members.

In this article, we will explore the concept of a private constructor, its uses, and how it can be implemented in C# programming.

CSharp Private Constructor
C# Private Constructor

C# Private Constructor

In C#, a private Constructor can be declared by using a private keyword. It doesn’t allow you to create an instance of a class if that class has only private constructors but no public constructors.

The main reason for creating a private constructor is to restrict the class from being instantiated when all its members are static.

Syntax:

The following is the syntax to define a private constructor in C#.

class A
    {
        // Private Constructor
        private A()
        {
         // Business logic code
        }
    }

What is the Use of a Private Constructor in C#?

A constructor is a special method that is called when an object of a class is created. A private constructor is a constructor that is declared private and can only be accessed within the same class. Private constructors are used for various purposes in C# programming. Some of the common uses are:

  • Private Constructor is used to prevent the creation of objects of a class.
  • It restrict access to a class.
  • Private constructor is used to implement a singleton pattern.
  • It Stops a class from being inherited.
  • It can be used to Implement a factory method pattern.

Private Constructor in C# with Scenarios Example

Let’s look at some scenarios where private constructors can be used in C# programming.

Scenario 1: Preventing the creation of objects of a class. 

Suppose we have a class named “Logger” for logging messages in an application. We want to ensure that only one instance of the Logger class is created throughout the application. To achieve this, we can declare the constructor of the Logger class as private. It will prevent the creation of objects of the Logger class from outside the class.

Example:

public class Logger
{
   private static Logger instance = null;
   private Logger() // Private constructor
   {
   }
   
   public static Logger GetInstance()
   {
      if (instance == null)
      {
         instance = new Logger();
      }
      return instance;
   }
}

In the above code example, the private constructor is used to prevent the creation of objects of the class from outside the class. A static instance variable is created to hold the single instance of the Logger class.

The GetInstance() method checks if the instance variable is null. If it is null, a new instance of the Logger class is created using the private constructor and assigned to the instance variable. If the instance variable is not null, the existing instance of the Logger class is returned.

This approach ensures that only one instance of the Logger class is created throughout the application. It can help prevent issues with concurrency and ensure that logging is consistent across the application.

Scenario 2: Restricting access to a class 

Suppose we have a class named “Admin” that contains sensitive information such as user passwords. We want to restrict access to the Admin class to only authorized users. 

To achieve this, we can declare the constructor of the Admin class as private. It will prevent the creation of objects of the Admin class from outside the class.

Example:

public class Admin
{
   private Admin() // Private constructor
   {
      // Implement logic to authenticate the user
   }
   
   public static Admin GetInstance()
   {
      // Implement logic to authenticate the user and create a single instance of Admin class
   }
}

Scenario 3: Implementing a singleton pattern using Private Constructor

A singleton is a design pattern that ensures that only one instance of a class is created throughout the application. 

To implement a singleton pattern, we can declare the Constructor of the class as private and create a static method that returns a single instance of the class.

Example:

public class Singleton
{
   private static Singleton instance = null;
   private Singleton() // Private constructor
   {
   }
   
   public static Singleton GetInstance()
   {
      if (instance == null)
      {
         instance = new Singleton();
      }
      return instance;
   }
}

The above code example shows how to create a Singleton class in C#.
The Singleton class has a private constructor to prevent the creation of objects of the class from outside the class.
A static instance variable is created to hold the single instance of the Singleton class.

The GetInstance() method checks if the instance variable is null. If it is null, a new Singleton class instance is created using the private Constructor and assigned to the instance variable. If the instance variable is not null, the existing instance of the Singleton class is returned.

Scenario 4. Using Private Constructor to Stop a class from being inherited

 Private constructors can also be used to prevent a class from being inherited. Any other class cannot inherit a class with a private constructor.

// Base class
   class A
    {
        // Private Constructor
        private A()
        {
        }
    }
 
// Derived class
   class B : A //Error
    {
        // 'A.A()' is inaccessible due to its protection level
    }

In the above code, we will get a compile-time error because the derived class B will fail to access the base class A constructor.

C# Private constructor Example 5:

A class with only private constructors cannot be explicitly instantiated outside the class. However, if a class has a private constructor and one or more public parameterized constructors, other classes can use the parameterized constructor to explicitly create an instance of that class.

using System;
namespace PrivateConstructor
{
   class A
    {
        // Private Constructor
        private A()
        {
        }
       // parameterized Constructor
        public A(int num)
        {
        }
    }    
    class Program
    {
        static void Main(string[] args)
        {
          // Default constructor
         // A obj1 = new A();   // Compile time error 
         
        //Parameterized Constructor               
            A obj2 = new A(10); // It will work fine.                                    
        } 
    }
    /* A obj1 = new A();// Error:
      'A.A()' is inaccessible due to its protection level.
    */
}

If we want to completely prevent the object creation of a class, either implicitly or explicitly, we must make all overloaded constructors private.

Key points about the private constructor

Following are a few important points about private constructors in C#:

  • private constructor is an instance constructor useful in classes with only static members.
  •  C# private constructor can be used to create a Singleton class.
  •  If a class has private constructors but no public constructors, other classes, except nested classes, are not allowed to create instances outside of that class.
  •  A private constructor class can have static and instance data members.
  •  A class that contains a private constructor can implement an interface or class.

Creating a singleton class using a private constructor in C#?

We can use the private constructor to create a Singleton class in C#.

  • The Singleton class ensures that only one instance of a class exists throughout an application’s lifetime. It is used to share data that is shared across the entire application.
  • The Singleton class is responsible for providing the same object to the user on demand.

Following is an example of creating a Singleton object using a private constructor in C#.

using System;
namespace PrivateConstructor
{
    public sealed class Singleton
    {
        //For the thread safety 
        private static Singleton instance = null;

        // Private constructor
        private Singleton()
        {
        }

        //Static property use to return instance of the class
        public static Singleton getInstance
        {
            get
            {
                if (instance == null)
                    instance = new Singleton();
                return instance;
            }
        }
        public void Print(string message)
        {
            Console.WriteLine(message);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
           // Singleton obj = new Singleton();//error

            Singleton obj = Singleton.getInstance;
            obj.Print("Hi Shekh");
            
            Console.ReadLine();
        } 
    }
    /* Output
       Hi Shekh

    */
}

How to control the number of objects created?

Here in this example, we are using the singleton class with a counter of the number of objects created, after which the static property getInstance will return null.

using System;
namespace PrivateConstructor
{
   class A
    {      
        public static int instanceCount = 0;
        // Private Constructor
        private A()
        {
            // Increment count by 1 everytime
            // a new object is created
            instanceCount++;
            Console.WriteLine($"Object {instanceCount} is created");
        }
        // Prorerty to return instance of the class
        public static  A getInstance
        {
            get
            {
                if (A.instanceCount < 3)
                {
                    return new A();
                }
                else
                {
                 Console.WriteLine("Maximum limit reached, You can't create new object");
                    return null;
                }
            }
        }
    } 
   
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                A obj =A.getInstance;
            }
        } 
    }
}
limit the object creation using private constructor
The output of the above program.

We can see in the above result that after the maximum instance limit is reached it doesn’t allow us to create a new object.

The following is the list of constructors available in C#.

Read more about constructors: Types of Constructors in C#

Summary:

This post provides detailed information on using private constructors and their benefits. The post also includes code examples that illustrate how C# private constructors can be used to create a Singleton class and to stop a class from being inherited. Overall, the post aims to help programmers understand the significance of private constructors and how to use them effectively in C# programming.

FAQs

Q: What is a private constructor in C#?

A private constructor is a constructor that is declared as private and can only be accessed within the same class.
Private constructors are used for various purposes in C# programming, such as preventing the creation of class objects, restricting class access, implementing a singleton pattern, and stopping a class from being inherited.

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

A private constructor is used to prevent the creation of objects of a class from outside the class. It also restricts access to a class, implements a singleton pattern, and stops a class from being inherited.

Q: Can we inherit a class with a private constructor in C#?

No, we cannot inherit a class with a private constructor in C#. A class with a private constructor cannot be inherited by any other class.

Q: What is Constructor in C#?

In C#, the Constructor is a special class method used to initialize data members of a class. The constructor name is the same as the class name and is automatically called when the class instance is created.

Q: Can we have public and private constructors in C#?

Yes, we can have public and private constructors in C#.

Q: What is the difference between a sealed class and a private constructor in C#?

In C#, a sealed class can’t be inherited, but it can be instantiated. A class with a private constructor, on the other hand, cannot be inherited or instantiated due to its protection level.

When to use Private Constructor?

A private constructor in C# is a constructor method with the “private” access modifier. It’s used to prevent the instantiation of a class from outside the class itself.

A private constructor is helpful when you want to restrict or manage the creation of instances, such as in the Singleton pattern, where you ensure only one instance of a class exists.

It can also be used when creating utility classes with static methods only or restricting class instantiation to factory methods within the same class.

References MSDN: Private Constructors

Articles to Check Out:

Shekh Ali
3 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments