Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization order of static readonly field [duplicate]

Tags:

c#

static

I'm curious of the C# spec says anything about the order of initializing static field's in C# 5 (.net4). For instance:

public class Test
{
   public static readonly string A = "hi";
   public static readonly string B = "bye";
   public static readonly string DEFAULT = A;
}

In testing (Mono 2.x) they seem to be initialized in the order they appear in code. eg. As is, DEFAULT will have the value "hi", but if I move the definition for DEFAULT above A and B, it will be assigned NULL because A hasn't been assigned yet.

Is there a guarantee that the variables are initialized in order? Or is it up to the compiler?

Thanks.

like image 757
zix99 Avatar asked Aug 10 '14 16:08

zix99


1 Answers

It is in the order that they appear in. See here.

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.

Also, when you have a static constructor:

If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

like image 117
Marcel N. Avatar answered Oct 22 '22 07:10

Marcel N.