I've done some searching and I think the following code is guaranteed to produce output:
B.X = 7
B.X = 0
A.X = 1
A = 1, B = 0
static class B
{
public static int X = 7;
static B() {
Console.WriteLine("B.X = " + X);
X = A.X;
Console.WriteLine("B.X = " + X);
}
}
static class A
{
public static int X = B.X + 1;
static A() {
Console.WriteLine("A.X = " + X);
}
}
static class Program
{
static void Main() {
Console.WriteLine("A = {0}, B = {1}", A.X, B.X);
}
}
I've run this numerous times and always get the output above the code section; I just wanted to verify it will never change? Even if textually, class A and class B are re-arranged?
Is it guaranteed that the first use of a static object will trigger the initialization of its static members, followed by instantiating its static constructor? For this program, using A.X in main will trigger the initialization of A.X, which in turn initializes B.X, then B() and after finishing the initialization of A.X, will proceed to A(). Finally Main() will output A.X and B.X.