Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# two classes with static members referring to each other

I wonder why this code doesn't end up in endless recursion. I guess it's connected to the automatic initialization of static members to default values, but can someone tell me "step by step" how does 'a' get the value of 2 and 'b' of 1?

public class A
{
    public static int a = B.b + 1;
}
public class B
{
    public static int b = A.a + 1;
}

static void Main(string[] args)
{
    Console.WriteLine("A.a={0}, B.b={1}", A.a, B.b); //A.a=2, B.b=1
    Console.Read();
}
like image 428
Jerry Avatar asked May 06 '10 21:05

Jerry


1 Answers

I would suppose:

  • A.a is queried, which causes the A static initializer to fire
  • This accesses B.b, causing the B static initializer to fire
  • A.a is queried; the type initializer is already activated (but no assignment has yet occurred), so the field (not yet assigned) is read as 0
  • 0 + 1 is 1, which is assigned to B.b <===========================
  • we now exit the B cctor and go back to the A cctor
  • 1 + 1 is 2, which is assigned to A.a <===========================
  • we now exit the A cctor
  • 2 is returned (WriteLine) for A.a
  • we query (on WriteLine) B.b; the cctor has already fired so we see 1
like image 168
Marc Gravell Avatar answered Nov 15 '22 17:11

Marc Gravell