Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Note: This blog has moved to omervk.wordpress.com.

Omer van Kloeten's Facebook profile

Omer has been professionally developing applications over the past 8 years, both at the IDF’s IT corps and later at the Sela Technology Center, but has had the programming bug ever since he can remember himself.
As a senior developer at NuConomy, a leading web analytics and advertising startup, he leads a wide range of technologies for its flagship products.

Get Firefox


powered by Dapper 

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

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.
Posted: Aug 19 2008, 05:09 PM by Omer van Kloeten | with 8 comment(s)
Filed under:

Comments

No Comments