2

I was stuck in between my code with the implementation of Static Code Initializers. Now, here I am calling the static field "x" of Classes A and B respectively in Main. Ideally, it should be generating the output as:

A : 0
A.x : 5
B : 0
B.x : 5  

But, it is generating the output as:

A : 0
B : 0
A.x : 5
B.x : 5  

Please explain.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class A
    {
        public static A _A = new A();
        public static int x = 5;
        public A()
        {
            Console.WriteLine("A : " + x);
        }
    }

    public class B
    {
        public static B _B = new B();
        public static int x = 5;
        public B()
        {
            Console.WriteLine("B : " + x);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("A.x : " + A.x);
            Console.WriteLine("B.x : " + B.x);
            Console.ReadKey();
        }
    }
}
gunr2171
  • 16,104
  • 25
  • 61
  • 88
Ajay
  • 643
  • 2
  • 10
  • 27
  • 2
    Since `A` and `B` don't declare static constructors, their field initializers are executed at an implementation-dependent time prior to the first use of a static field of each class. In this case the CLR chose to execute both field initializers at the beginning of Main. – Michael Liu Jul 21 '14 at 19:11
  • 1
    To get the behavior you're expecting, add empty static constructors to `A` and `B` (`static A() { }` and `static B() { }`). – Michael Liu Jul 21 '14 at 19:18
  • @Micahel Liu I commented out both Writeline functions in Main Method, but then there was no output being generated.Ideally, I was expecting output as A:0 and B:0(as per your answer). – Ajay Jul 21 '14 at 19:22
  • If you comment out the calls to WriteLine, then the "first use" never occurs, so the CLR may choose not to execute the field initializers at all. Try adding empty static constructors. – Michael Liu Jul 21 '14 at 19:24
  • @MichaelLiu Adding empty Static Constructors worked.....Thanks man – Ajay Jul 21 '14 at 19:28

2 Answers2

1

Static initialization of fields happens in non-deterministic order, try making the constructors of A and B static, and initialize the variables inside. That ensure it is initialized the first time your class is used and in the order you specified.

NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61
0

The CLR first analyzes the code in your main:

Here 2 static classes are used and hence will resolve the constructors of both in the order in which they are used.

Hence the Writeline inside the constructors are executed first and then WriteLine of your main code is executed.

If you had used Console.WriteLine for B first in main, followed by A, then B's constructor will execute first.

Rockstart
  • 2,337
  • 5
  • 30
  • 59