Which came first the static chicken or the static egg?

Came across an interesting thing to do with static constructors in the course of the development of ANTS Profiler 3. We got around to talking about static constructors across multiple files and wondering what would happen if you attempted to create a circular reference of static initialisers. In the result you can see that the circular reference works exactly as you would expect. The static member variables being initialised to the default before any code got run so that wasn’t interesting. However what if one of them is instantiated to a value and you refer to that value in the static method to instantiate another member variable (say for example opening a log file or something?) what would happen then?

So we come to the code:

using System;
namespace RedGate
{
   partial class ChickenOrEgg
   {
         static string egg = ValueOfChicken();
         static string ValueOfEgg()
      {
            return egg;
      }
      static void Main(string[] args)
      {
         Console.WriteLine(“chicken={0} egg={1}”, chicken, egg);
         Console.WriteLine(“Press any key…”);
         Console.ReadKey();
      }
   }
   partial class ChickenOrEgg
   {
      static string chicken = “Chicken”; // ValueOfEgg();
      static string ValueOfChicken()
     {
         return chicken;
     }
   }
}

 

So what do we expect the output of this program to be? Well personally I would have thought…

chicken=Chicken egg=Chicken

The system noticing that the chicken member variable is set to be a static string so instantiating it first. But no the actual output of the program is…

chicken=Chicken egg=

So it’s obvious that even though you would expect the static chicken string to be instantiated first as it has no dependencies that doesn’t happen and if you look at the compiled code in Reflector you can see what the static constructor actually is.

static ChickenOrEgg()
{
      ChickenOrEgg.egg = ChickenOrEgg.ValueOfChicken();
      ChickenOrEgg.chicken = “Chicken”;
}

So here’s a warning to all of you out there, don’t assume anything about the order in which your static initialisers get called as it will only cause pain.

The answer to the initial question – the static chicken 🙂