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();
}
I would suppose:
A.a is queried, which causes the A static initializer to fireB.b, causing the B static initializer to fireA.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 <===========================B cctor and go back to the A cctor1 + 1 is 2, which is assigned to A.a <===========================A cctor2 is returned (WriteLine) for A.a
WriteLine) B.b; the cctor has already fired so we see 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With