Can two static variables which refer to each other cause an infinite recursion?
public class A
{
public static int a = B.b + 1;
}
public class B
{
public static int b = A.a + 1;
}
public class MainClass
{
public static void Main()
{
Console.WriteLine( "A.a={0}, B.b={1}", A.a, B.b );
}
}
Can you explain what would be the output (if any) of the above code without actually running it?
This will not cause an infinite recursion, because initialization expressions will be evaluated just once. The output should be:
ReplyDeleteA.a=2, B.b=1
1. Static constructor of class A is called.
2. Before the field A.a is initialized, static constructor of class B is called.
3. Field B.b is being initialized. A.a is not initialized and has a default value of 0. It is incremented by 1 and stored in B.b. The field value is now equal to 1.
4. Field A.a is being initialized. B.b is initialized and has a value of 1. It is incremented by 1 and stored in A.a. The field value is now equal to 2.
Why constructor of class B is called first?
ReplyDeleteConstructor for class B is called first because while passing arguments in the Console.WriteLine, arguments are passed from right to left.
ReplyDelete