Does C# resolve dependencies among static data members automatically?
Asked Answered
C

2

9

If one static data member depends on another static data member, does C#/.NET guarantee the depended static member is initialized before the dependent member?

For example, we have one class like:

class Foo
{
    public static string a = "abc";

    public static string b = Foo.a + "def";
}

When Foo.b is accessed, is it always "abcdef" or can be "def"?

If this is not guaranteed, is there any better way to make sure depended member initialized first?

Connubial answered 13/11, 2009 at 5:30 Comment(0)
W
9

Like said before, static field initialization is deterministic and goes according to the textual declaration ordering.

Take this, for example:

class Foo
{
    public static string b = a + "def";
    public static string a = "abc";
}

Foo.b will always result in "def".

For that matter, when there is a dependency between static fields, it is better to use a static initializer :

class Foo
{
    public static string b;
    public static string a;

    static Foo()
    {
        a = "abc";
        b = a + "def";
    }
}

That way, you explicitly express your concern about the initialization order; or dependency for that matter (even if the compiler won't help if you accidentally swap the initialization statements.) The above will have the expected values stored in a and b (respectively "abc" and "abcdef").

However, things might get twisty (and implementation specific) for the initialization of static fields defined in multiple classes. The section 10.4.5.1 Static field initialization of the language specification talks about it some more.

Wale answered 13/11, 2009 at 5:51 Comment(0)
B
2

It will show allways "abcdef", because initialization goes top down in source, today just like before.

All static members will be initialized upon loading of the classtype holding them.

Banshee answered 13/11, 2009 at 5:36 Comment(1)
Which in turn means that if a maintenance programmer swaps those two lines, so that b = a + "def" comes first, b will then get initialised to "def", because a was null when b got initialised. I.e. by doing something like this, you take a dependency on the order of declaration.Graminivorous

© 2022 - 2024 — McMap. All rights reserved.