Order of static constructors/initializers in C#

2019-01-18 10:27发布

While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this:

static private List<int> a = new List<int>() { 0 };
static private List<int> b = new List<int>() { a[0] };

Without doing anything special that worked. Is that just luck? Does C# have rules to resolve this?

Edit: (re: Panos) In a file lexical order seems to be king? what about across files?

In looking I tried a cyclical dependency like this:

static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { a[0] };

and the program didn't run the same (the test suit failed across the board and I didn't look further).

4条回答
我想做一个坏孩纸
2楼-- · 2019-01-18 10:29

See section 10.4 of the C# spec for the rules here:

when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order. Likewise, when an instance of a class is created, all instance fields in that instance are first initialized to their default values, and then the instance field initializers are executed in textual order. It is possible for static fields with variable initializers to be observed in their default value state. However, this is strongly discouraged as a matter of style.

So in other words, in your example 'b' is initialized to its default state (null) and so the reference to it in the initializer of 'a' is legal but would result in a NullReferenceException.

These rules are different to Java's (see section 8.3.2.3 of the JLS for Java's rules about forward references, which are more restrictive).

查看更多
该账号已被封号
3楼-- · 2019-01-18 10:31

It seems to depend on the sequence of lines. This code works:

static private List<int> a = new List<int>() { 1 };
static private List<int> b = new List<int>() { a[0] };

while this code does not work (it throws a NullReferenceException)

static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { 1 };

So, obviously no rules for cyclical dependency exist. It's peculiar however that the compiler does not complain...


EDIT - What's happening "across files"? If we declare these two classes:

public class A {
    public static List<int> a = new List<int>() { B.b[0] };
}
public class B {
    public static List<int> b = new List<int>() { A.a[0] };
}

and try to access them with this code:

try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); }
try { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }
try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }

we are getting this output:

The type initializer for 'A' threw an exception.
Object reference not set to an instance of an object.
The type initializer for 'A' threw an exception.

So the initialization of B causes an exception in static constructor A and lefts field a with the default value (null). Since a is null, b can not also be initialized properly.

If we do not have cyclical dependencies, everything works fine.


EDIT: Just in case you didn't read the comments, Jon Skeet provides a very interesting reading: The differences between static constructors and type initializers.

查看更多
淡お忘
4楼-- · 2019-01-18 10:46

Personally I would get rid of the static initializers since it isn't clear and add a static constructor to initialize these variables.

static private List<int> a;
static private List<int> b;

static SomeClass()
{
    a = new List<int>() { 0 };
    b = new List<int>() { a[0] };
}

Then you don't have to guess what is going on and you're being clear in your intentions.

查看更多
Bombasti
5楼-- · 2019-01-18 10:48

Yes, you were lucky. C# appears to execute the code in the order it appears in the class.

static private List<int> a = new List<int>() { 0 };
static private List<int> b = new List<int>() { a[0] };

Will work but ...

static private List<int> b = new List<int>() { a[0] };
static private List<int> a = new List<int>() { 0 };

Will fail.

I would recommend putting all your dependencies in one place, the static constructor is the place for this.

static MyClass()
{
  a = new List<int>() { 0 };
  b = new List<int>() { a[0] };
}
查看更多
登录 后发表回答