-1

I read on MSDN that the output of

using System;
class Test
{
   static void Main() 
   {
      Console.WriteLine("{0} {1}", B.Y, A.X);
   }

   public static int F(string s) 
   {
      Console.WriteLine(s);
      return 1;
   }
}

class A
{
   public static int X = Test.F("Init A");
}

class B
{
   public static int Y = Test.F("Init B");
}

can be either of

Init A 
Init B
1 1

or

Init B
Init A
1 1

but I can't figure out why the order of excecution of X's initializer and Y's initializer could occur in either order?

I always get the second result (which I expected) on my system but cannot see how the first one could also be achieved?

Thanks.

MethodMan
  • 18,625
  • 6
  • 34
  • 52
user3723486
  • 189
  • 1
  • 3
  • 12
  • It is not saying a particular runtime implementation will produce either output at random. It is saying the runtime implementor can execute static field initializers in an order of their choosing, resulting in either output. There may not exist an implementation that produces the first output. – Mike Zboray Nov 13 '15 at 17:35

1 Answers1

2

You're reading from the language specification, which tells you what is allowed to happen according the specification of the language. You're seeing a consistent behaviour in the particular implementation of the language that you're using, and that behaviour is consistent with the specification, so all is well.

What the language specification is warning you is that you shouldn't rely on that behaviour in your program, since in a future version of the runtime (or on a different processor / platform / day of the week), the behaviour could change.

Jon G
  • 4,083
  • 22
  • 27