13

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?

0

3 Answers 3

26

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Better yet, take out the initializer for field entirely. All fields are preset to zero (or null) when the object is first created (for static fields, when the type is first loaded).
7

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.

1 Comment

+1 Thanks for the link to .NET Fiddle, brilliant tool.
3

Switch the order of the static variables.

private static int field = 0;
public static SomeSingleton Default = new SomeSingleton();

In your code, the constructor runs first, which sets field, and then field overrides its value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.