Blog

Filter posts by the Tags of Blog section!

Private constructor in C#

Monday, 18 February 2019

In C#, you can create private constructors. It is used in a class that contains static members only. You can NOT instantiate from a class that has a private constructor with the same parameters. The main purpose of a private constructor is to restrict the class from being instantiated. Take a look at the following class:

 

public class BaseClass
{
 
    private BaseClass()
    {
 
    }
}

If you try to instantiate the above class, you will get the following error:

 

BaseClass baseClass=new BaseClass(); //'BaseClass.BaseClass()' is inaccessible due to its protection level [PrivateConstructor]

 

 

But you can have another public or private constructor in the same class:

 

public class BaseClass
{
 
    private BaseClass()
    {
 
    }
 
    public BaseClass(string a)
    {
        A = a;
    }
 
    public static string A { get; set; }
}

 

Another usage of the private constructor is when It is used in singleton design patterns, to make sure that only one instance of a class can be created.

 

private static BaseClass instance = null;
    public static BaseClass getInstance()  
    {  
        if (instance == null)  
        {  
            instance = new BaseClass();  
        }  
        return instance;  
    }  

 

Now, what’s the difference between creating a class with a private constructor and defining it as sealed!?

Tags: C#

comments powered by Disqus