C# Private Constructor

In this article, we will learn about the Private constructor in C# with multiple examples.
First of all, Constructor in C# is the special method of the class which is used to initialize the data members of the new object. Every class in C# must have a constructor which gets automatically invoked when the new object of the class is created.

C# Private Constructor

Private constructor: In C#, A parameterless constructor with a   private  access modifier in a class is known as a private constructor. It is a special instance constructor which is mainly used to control the instantiation of a class.

A Private constructor is generally used with the class having static data members only.

The main intention behind the private constructor is to control the object creation and to stop explicit inheritance.

    • Private constructors can be useful when creating a Singleton class, where we use a static function or property to obtain an instance of the class rather than explicit instantiation.
    • Apart from creating a Singleton object, a private constructor can be used to prevent a class from being inherited by other classes except for nested classes.
    • It is useful when we want the caller of the class only to use the class but not instantiate.
    • A class having only private constructors can’t be instantiated or inherited explicitly. However, It allows us to create an object of the class inside the class methods itself.
    • If a class contains a private constructor and one or more public parameterized constructors, then the other classes are allowed to create an instance for that class explicitly by using the parameterized constructor.
    • 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.
    • A private constructor is useful in classes that contain only static members.

 

Private Constructor Syntax

The following is the syntax to define a private constructor.

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

Prevent a class from being inherited

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

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

Prevent a class from being instantiated

A class having only private constructors can’t be instantiated explicitly by the other classes in C#. But If a class contains a private constructor and one or more public parameterized constructors, then the other classes are allowed to create an instance for that class explicitly by using the parameterized constructor.

using System;
namespace PrivateConstructor
{
   class A
    {
        // Private Constructor
        private A()
        {
        }
       // parameterized Constructor
        private A(int num)
        {
        }
    }    
    class Program
    {
        static void Main(string[] args)
        {
          
         // A obj1 = new A();   //Compile time error 
                              
            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 from implicitly or explicitly, we need to make all the overloaded constructors as private.

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. It is used to preserve the global state of a type and to share common data across the whole application.

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

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

    */
}

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 reached it doesn’t allow us to create a new object.

Types of Constructors in C#

The following are the types of constructors available in C#.

For more details about the constructors, please read my previous post Types of Constructor in C#.

Conclusion:

In this article, we learned about private constructor in C# with multiple examples. I hope you enjoyed this post and found it useful. In case you have any doubt, please post your feedback, question, or comments.

Leave a Reply