Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public constructor and static constructor

I am reading a code in C# that uses two constructors. One is static and the other is public. What is the difference between these two constructors? And for what we have to use static constructors?

like image 725
Strider007 Avatar asked Jun 08 '10 07:06

Strider007


People also ask

What is difference between static constructor and private constructor?

Static constructor is called before the first instance of class is created, wheras private constructor is called after the first instance of class is created. 2. Static constructor will be executed only once, whereas private constructor is executed everytime, whenever it is called.

What is a static constructor?

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

What is the difference between static and default constructor?

Static constructor runs once per AppDomain just before you access the instance of class first time. You can use it to initialize static variables. On the other hand default constructor runs every time you create new instance of the class. in default constructor you can initialize non-static fields of the instance.

Can static class have public constructor?

Yes, we can create a constructor of static class, but constructor should be static with no parameter and without access modifier.


1 Answers

static and public are orthogonal concepts (i.e. they don’t have anything to do with each other).

public simply means that users of the class can call that constructor (as opposed to, say, private).

static means that the method (in this case the constructor) belongs not to an instance of a class but to the “class itself”. In particular, a static constructor is called once, automatically, when the class is used for the first time.

Furthermore, a static constructor cannot be made public or private since it cannot be called manually; it’s only called by the .NET runtime itself – so marking it as public wouldn’t be meaningful.

like image 158
Konrad Rudolph Avatar answered Sep 19 '22 06:09

Konrad Rudolph