Pitfall: Static Field Inline Initialization Order of Execution

Lean by Katayun, CC-BY-NC-SA Here’s something I fell into today. You have a class that has some members that need to be calculated once. So you use static readonly fields. One of those members is a calculation of some of those members. Take the following code for instance:

public class StaticDemo
{
static readonly int Sum = A + B;
static readonly int A = Calculator.GetA();
static readonly int B = Calculator.GetB();
}

This code will initialize A and B from the Calculator class and initialize Sum from the sum of A and B. However, when you run this code, Sum will equal 0, no matter what A or B are.

Why is this? Apparently, when initializing static fields inline, the order of execution is from top to bottom, regardless of dependencies. Trying to use the same method to initialize an instance field will result in the error A field initializer cannot reference the non-static field, method, or property.

So how do we solve this, you ask?

public class StaticDemo
{
static readonly int A = Calculator.GetA();
static readonly int B = Calculator.GetB();
static readonly int Sum = A + B;
}

Now Sum will really equal the sum of A and B. Simple, but a sure-fire pitfall if you don’t know it.

Advertisements

7 thoughts on “Pitfall: Static Field Inline Initialization Order of Execution

  1. I think that in this case I would have used a static constructor to initialize all fields. This would make the fact that we are depending on the order more explicit.

  2. Another solution for the code above, although sum isn’t readonly, but it will cose additional IL instruction so I can live with this :-)
    public class StaticDemo
    {
    static int Sum {get { return A + B;} }
    static readonly int A = Calculator.GetA();
    static readonly int B = Calculator.GetB();
    }

  3. For reference purposes only, sections 10.4.5.1 and 10.4.5.2 of the C# language specification precisely outline this behavior and also why it doesn’t work this way for instance members.
    -Bart

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s