I'm able to compile and run the following program successfully:
class MyClass1
{
public static int x = y;
public static int y = 10;
}
static void Main(string[] args)
{
Console.WriteLine(MyClass1.x); //prints 0
Console.WriteLine(MyClass1.y); //prints 10
}
Why it is compiling successfully? How does x
gets the value of y
even before it is declared and initialized? The same gets compile time error had it been the case of instance fields.
From ECMA-334 - 17.4.5.1 Static field initialization
The static field variable initializers of a class declaration correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§17.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.
So y
variable is used in the line of initialization of x
variable and get initialized with default value which is 0