C# Private Constructor with example

Private constructors are used to prevent creating an instance of a class if it has no instance fields or methods. They are basically used in class that contains only static members.

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

CSharp Private Constructor
C# Private Constructor

C# Private Constructor

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 of 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
        }
    }

Key points about the private constructor

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

  • A private constructor is an instance constructor that is 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 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.

C# Private Constructor Example 1:

The following code example demonstrates that a class with a private constructor is not explicitly inherited by other classes.

// 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 2:

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.

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#

FAQ

What is the purpose to create a 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.

Can we have public and private constructors in C#?

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

Conclusion:

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

If you found this post helpful, please leave a comment and share it with others. Thanks.

References MSDN: Private Constructors

Articles to Check Out:

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments