Introduction:

In this article we will explain how to use Private Constructor or what is Private Constructor in c# or how to use Private Constructor Or how to invoke Private Constructor in c# with example.

Description:

The Private Constructor in c# is a special instance constructor and It is generally used in classes that contain static members only. 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 Example

Following is the example of creating a private constructor in c# to prevent other classes  to create an instance of particular class.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace SQLTutorialsPoint
{
    public class Customer
    {
        //private Constructor
        private Customer()
        {
            Console.WriteLine("I am Private Constructor");
        }
        public static string name, location;
        // Default Constructor
        public Customer(string a, string b)
        {
            name = a;
            location = b;
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
    //following comment line will throw an error because constructor is inaccessible
            //Customer user = new Customer();
 
            // Only Default constructor with parameters will invoke
            Customer Customer1 = new Customer("Aditya Patel", "uttar pradesh");
            Console.WriteLine(Customer.name + ", " + Customer.location);
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
    }
 
}

 

As you see above example, we created a class with private constructor and default constructor with parameters. If you uncomment the commented line (Customer user = new Customer();), 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.

 How to Use Private Constructor in C# with Example

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

 

I hope ti will help to you after reading.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like