I've come across a C# behavior that I would like to understand. Consider a class like this:
public class SomeSingleton
{
public static SomeSingleton Default = new SomeSingleton();
private static int field = 0;
private SomeSingleton()
{
field = 1;
}
public int GetField()
{
return field;
}
}
Now, let's call GetField() method:
var field = SomeSingleton.Default.GetField();
I am getting 0
as if the instance constructor was skipped. Why?
Just swap the order of field
declaration before Default
.
So your lines:
public static SomeSingleton Default = new SomeSingleton();
private static int field = 0;
should be:
private static int field = 0;
public static SomeSingleton Default = new SomeSingleton();
The reason is due to field initialization order. First Default
is initialized in your code, which assigns field
value of 1
. Later that field is assigned 0
in initialization. Hence you see the latest value of 0
and not 1
.
See: 10.4.5.1 Static field initialization
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.
This is because the ordering of the static
variables. If you switch the two statements, the output becomes 1
:
private static int field = 0;
public static SomeSingleton Default = new SomeSingleton();
This is expected behavior as documented in MSDN: Static field initialization.
See this .NET Fiddle.
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