Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# static field, instance constructor

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?

like image 942
Piotr Avatar asked Jul 24 '14 15:07

Piotr


2 Answers

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.

like image 110
Habib Avatar answered Oct 11 '22 10:10

Habib


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.

like image 32
Patrick Hofman Avatar answered Oct 11 '22 11:10

Patrick Hofman