title: Is the order of static class initialization in C# deterministic?
body: <p>I've done some searching and I think the following code is guaranteed to produce output:</p>
  
  <pre><code>B.X = 7
  
  B.X = 0
  
  A.X = 1
  
  A = 1, B = 0
  </code></pre>
  
  
  
  <pre><code>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);
      }
  }
  </code></pre>
  
  <p>I've run this numerous times and always get the output above the code section; I just wanted to verify will it change?  Even if textually, class <code>A</code> and class <code>B</code> are re-arranged?  </p>
  
  <p>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 <code>A.X</code> in main will trigger the initialization of <code>A.X</code>, which in turn initializes <code>B.X</code>, then <code>B()</code> and after finishing the initialization of <code>A.X</code>, will proceed to <code>A()</code>.  Finally, <code>Main()</code> will output <code>A.X</code> and B.X`.</p>