First of all, I got an answer in What is the use of static constructors?, but I want an answer in this context.
Here is my C# static class:
public static class BasicClass
{
static int i = 0;
static BasicClass()
{
i = 10;
}
public static void Temp()
{
//some code
}
public static void Temp1()
{
//some code
}
}
Inside this I have a static variable i
which is initialized to 10 when it is first called. So basically it may be the purpose of a static constructor but the same thing can be achieved without declaring a static constructor by initializing the static int i = 10
which serves the same purpose that is gets initialized only once.
Then why do we need a static constructor? Or am I completely wrong in understanding the concept or use of static constructors?
Well, in your example it is not indeed needed, but and imagine when i
value has to be read from a database, text file, or any other resource? You might need something like:
static BasicClass()
{
using (SomeConnection con = Provider.OpenConnection())
{
try
{
// Some code here
}
catch
{
// Handling expeptions, setting default value
i = 10;
}
}
}
Now it is not possible to declare and initialize your static field, you're better served using a static constructor
If you compile that class into an assembly, then use ILSpy or similar to disassemble the result, you will notice that all static member initialization is performed in the static constructor.
For instance, the following C# code:
public static class BasicClass
{
static int i = 10;
}
Will produce IL equivalent to:
public static class BasicClass
{
static int i;
static BasicClass()
{
i = 10;
}
}
In other words, direct initialization is only syntactic sugar provided by the C# compiler. Under the hood, a static constructor is still implemented.
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