Private Constructor in C#

You must be thinking why do we need private constructor in C#, when it cannot be accessed, how we will create it's instance? Right? and you are right here, private constructors are used when we don't want to create instance of class.

So, what's the use of private constructor? Exactly?

Private constructors is a special instance constructor. and are used in some cases where we create a class which only have static members, so creating instance of this class is useless, and that is where private constructor comes into play.

If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.

Consider this class with private constructor

class LogClass
{
    public static double e = Math.E;  //2.71828

    // Private Constructor:
    private LogClass() { 

    }
   
}

The declaration of the empty constructor prevents the automatic generation of a parameterless constructor.

If you do not use an access modifier with the constructor it will still be private by default.

Example of Private constructor

   using System;
   public class Sample {
	    public static int a=10,b=15;
		private Sample()
        {  
		}

		public static int sum()
		{
			return a + b;
		}
	}

	public class PrivateConstructorProgram {
		public  static void Main(string[] args)
		{
			// calling the private constructor using class name directly 
			int result = Sample.sum();
			Console.WriteLine(result);
			
			// Below code will throw the error as we can't create object of this class
			// Sample objClass = new Sample(); 
		}
	}

Output;

25

As you can see in the above example, we are not creating Object of the class and directly calling it's method.

Where to use Private constrctors in C#

Private constructors are useful in cases where it is undesirable for a class to be created by code outside of the class. You can use private constructor, when

  • To restrict a class from being inherited.
  • Restrict a class being instantiate or creating multiple instance/object.
  • To achieve the singleton design pattern.

You might also like to read:

C# Constructors and Destructors

Abstract Class in C#

C# Class and Objects

C# Inheritance

C# for loop

C# while loop

C# do while loop


Share Tweet