In c#, Private Constructor is a special instance constructor, and it is useful in classes that contain only static members. If a class contains one or more private constructors and no public constructors, then the other classes are not allowed to create an instance for that particular class except nested classes.
Following is the syntax of defining a private constructor in the c# programming language.
If you observe the above syntax, we created a private constructor without any parameters to prevent an automatic generation of the default constructor. If we didn’t use any access modifier to define the constructor, then by default, it will treat it as private.
Following is the example of creating a private constructor in the c# programming language to prevent other classes from creating an instance of a particular class.
If you observe the above example, we created a class with a private constructor and a default constructor with parameters. If you uncomment the commented line (User user = new User();), then it will throw an error because the constructor is private, so it won’t allow you to create an instance for that class.
Here we are accessing class properties directly with the class name because those are static properties, so it won’t allow you to access the instance name.
When you execute the above c# program, you will get the result below.
This is how you can use a private constructor in the c# programming language to prevent creating an instance of a particular class based on our requirements.