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?
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.
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.
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.
Yes, we can create a constructor of static class, but constructor should be static with no parameter and without access modifier.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With