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.

6 Comments

Comments have been disabled for this content.