-1

I have this this two codes:

private static int a = 5;
private static int b = a;

static void Main(string[] args)
{
    Console.WriteLine(b);
}

And

private static int b = a;
private static int a = 5;

static void Main(string[] args)
{
    Console.WriteLine(b);
}

Please explain to me why in the first case output is 5, but in the second one output is 0

Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46

1 Answers1

9

In the second case compiler will generate the following static constructor for type:

static Program()
{
   // Note: this type is marked as 'beforefieldinit'.
   Program.b = Program.a;
   Program.a = 5;
}

So, a equals 0 when it assign to b. Then a set to 5

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116