Difference between static and private constructor in C#

Let us explain what is static and private constructor in C#?

 

Posted: April 8, 2020. | By: mustafa

What is static and private constructor in C#?

Static Constructor is called automatically before the first instance of the class or any static data is referenced. For any number of classes instances it will be called once.

And private constructor is used to prevent a class to be instantiated. But, if a class has other public constructors, then that constructor can be instantiated from the object. Also a class can have multiple private constructor and that can be called by another constructors.

Then which constructor is called first in C# static or private?

Static constructor will be called first as a static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

What is the use of private constructor in C#?

Private constructors are used to prevent creating instances of a class. A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class. For example:

class NLog
{
 // Private Constructor:
 private NLog() { }

public static double e = Math.E; //2.71828...
 
 // Nested Class
 class TestException() 
 {
 NLog log = new NLog();
 }
}

class Program
{
static void Main(string[] args)
{
// The following commented line will throw an error because constructor is not accessible

//NLog log = new NLog();
}
}

The declaration of the empty constructor prevents the automatic generation of a parameterless constructor. Note that if you do not use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.
If all the methods in the class are static, consider making the complete class static. 

Difference between static and private constructor in C#

 

PrivateStatic
This is the constructor whose access modifier is private.Constructor is having access modifier as static.
Private constructor is used to prevent a class to be instantiated.Static constructor is used to initialize static members of a class. It is called by CLR, not by creating instance of the class.
Private constructor is called after the instance of the class is created.Executes before the first instance of a class. We can not determine the time of execution.
The class can have many private constructorsA class can have only one static constructor.
Private constructor can have many parameters.Static constructor has no parameter.

related posts

Back to top