0
private static string Test = a ? "test" : "hello";
private static bool a = Test == "test";

These seem to be reliant upon each other, but at compile time become a = false" Test = "hello" regardless of the order. I think it has something to do with booleans being set to false but if someone could explain how this compiles that would be nice.

Luke Murray
  • 861
  • 8
  • 10
  • The order is only irrelevant because you get the same result in both cases. If you set `a` first, `Test` will be `null`, if you set `Test` first, `a` will be `false`. – Charles Mager Aug 13 '16 at 16:47
  • Perhaps the reference will help https://msdn.microsoft.com/en-us/library/aa645758(v=vs.71).aspx – Steve Aug 13 '16 at 16:48

2 Answers2

4

Based one the C# Language specifications:

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.

private static string Test = a ? "test" : "hello"; // a is false - default for bool

Now Test refers to the string "hello"

private static bool a = Test == "test"; // a remains false as Test != "test"
Zein Makki
  • 29,485
  • 6
  • 52
  • 63
0

This compiles because all the names are visible in the scope. It produces the results you experience because of default initialization of variables to 0 and order of execution.

GreatAndPowerfulOz
  • 1,767
  • 13
  • 19