What is issue if we make class constructor private in C# Programming?

If we make the constructor private of a class in C# programming then we cannot create an object of the class out side of it and also, no class can be inherited from this class.

Cannot create an object of class in C# Program

As constructor is private, it is not available outside of the class.We have a class A having private constructor. If we try to create object in Main method, compiler will flash an error.

    class Program
    {
        //Class having private constructor
        class A
        {
            //Make constructor private to prevent object creation
            //of this class from outside.
            private A() { }
        }

        static void Main(string[] args)
        {
            //Cannot create object of baseError as base constructor is private.
            A a = new A();//Error:'A.A()' is inaccessible due to its protection level

            
        }
    }

No class can be derived from the class in C# Program:

As, we know that if we create an object of derived class, the base class constructor will be called first automatically. As, base class constructor is private, it’s not accessible to derived class and cannot be called from derived class, hence compiler error.We have a class Base having private constructor. If we try to derive a class from it, compiler will flash an error.

class Base
{    
    private Base() { }//private constructor

    public void method() { }
    
}

//As soon as we write class Derived:Base, here itself compiler will flash an error

class Derived : Base//Error	:'Base.Base()' is inaccessible due to its protection level
{
   
}

NOTES:

However, there are use of private constructor in C# programming.

Generally, we make the constructor private if we don’t want to allow object creation outside of this class. Or, want to have utility classes in C# software projects, where we keep only utility functions that are static. So, without creating the object, we can call functions with class name only. Since, we have only functions/algorithms in the class, creating object is useless.

Related Posts