C# Private Constructor with example

In this post, we’ll go over the private constructor in C# with various examples.

CSharp Private Constructor
C# Private Constructor

C# Private Constructor

Private Constructor in C# is a special instance constructor that is commonly used in classes with only static members. If a class has one or more private constructors but no public constructors, other classes, except nested classes, are not allowed to make instances of that class.

Note: It’s important to note that if you don’t provide an access modifier, the constructor will stay private by default. The private modifier, on the other hand, is usually used to specify that a class cannot be instantiated explicitly.

Private Constructor Syntax

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

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

C# Private Constructor: Points to remember

The following are the few key factors to remember regarding the Private constructor in C#.

    • Use the private constructor when a class contains only static members.
    • Private constructor in C# can be used to create a Singleton class.
    • If a class has one or more private constructors but no public constructors, other classes, except nested classes, are not allowed to create instances outside of that class.
    • It is useful when we want the caller of the class only to use the class but not instantiate.
    • It’s prohibited to explicitly instantiate or inherit a class with just private constructors. It does, however, permit us to create a class object within the class methods.
    • A class with a private constructor can have both static and instance data members.
    • A class that contains a private constructor can implement an interface or class.

Example 1: Private Constructor prevent a class from being inherited

We can use the private constructor in C# If we don’t allow a class to be inherited explicitly by the other classes.

Following is the example.

// 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.

Example 2: Private consturctor

In C#, a class with only private constructors cannot be explicitly instantiated outside the class. If a class has a private constructor and one or more public parameterized constructors, other classes can use the parameterized constructor to explicitly generate 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.
    */
}

In case if we want to prevent object creation of a class completely either implicitly or explicitly, we need to make all the overloaded constructors private.

How to create a singleton class using a private constructor?

In C#, we use the private constructor to create a Singleton class.

The  Singleton  class ensures that only one instance of a class can exist throughout the lifetime of an application. Singleton object is used to share common data across the whole application.

Singleton class itself is responsible to provide the same object again and again on user demand.

Following is the 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 object creation?

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 are the 5 types of constructors available in C#.

Please see my earlier post for more information regarding constructors: Types of Constructor in C#

What is the purpose to create the private constructor within a class?

1. Private constructor is used to preventing a class from being inherited.
2. To limit the number of times a class can be instantiated.
3. It is used to achieve the singleton design pattern.

What is Constructor in C#?

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

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.

Conclusion:

In this article, we learned about the private constructor in C# with various examples.

Thank you for taking the time to read the blog, if you find it interesting, please like, comment, and share it with others. Thanks.

References MSDN: Private Constructors

Articles to Check Out

Leave a Comment