C# Private Constructor with Examples

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.

C# Private Constructor Syntax

Following is the syntax of defining a private constructor in the c# programming language.

 

class User
{
   // Private Constructor
   private User()
   {
       // Your Custom Code
   }
}

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.

C# Private Constructor Example

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.

 

using System;

namespace Tutlane
{
    class User
    {
       // Private Constructor
       private User()
       {
          Console.WriteLine("I am Private Constructor");
       }
       public static string name, location;
       // Default Constructor
       public User(string a, string b)
       {
          name = a;
          location = b;
       }
    }
    class Program
    {
       static void Main(string[] args)
       {
          // The following comment line will throw an error because the constructor is inaccessible
          //User user = new User();

          // Only the Default constructor with parameters will invoke
          User user1 = new User("Suresh Dasari", "Hyderabad");
          Console.WriteLine(User.name + ", " + User.location);
          Console.WriteLine("\nPress Enter Key to Exit..");
          Console.ReadLine();
       }
    }
}

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.

 

C# Private Constructor Example Result

 

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.