C# Private Constructor with Examples

In c#, Private Constructor is a special instance constructor and it is used in a classes that contains 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 c# programming language.

 

 class User

  {

      // Private Constructor

      private User()

       {

           // Your Custom Code

       }

  }

If you observe above syntax, we created a private constructor without having any parameters that means it will prevent an automatic generation of default constructor. In case, if we didn’t use any access modifier to define constructor, then by default it will treat it as a private.

C# Private Constructor Example

Following is the example of creating a private constructor in c# programming language to prevent other classes to create an instance of 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 constructor is inaccessible

            //User user = new User();

 

            // Only 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 above example, we created a class with private constructor and default constructor with parameters. If you uncomment the commented line (User user = new User();), then it will throw an error because the constructor is a private so it won’t allow you to create an instance for that class.

 

Here we are accessing class properties directly with class name because those are static properties so it won’t allow you to access with instance name.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Private Constructor Example Result

 

This is how we can use private constructor in c# programming language to prevent creating an instance of particular class based on our requirements.

Topics Covered