C# Brainteaser Order it

What will be displayed, why, and how confident are you?

using System;

class Foo
{
static Foo()
{
Console.WriteLine ("Foo");
}
}

class Bar
{
static int i = Init();

static int Init()
{
Console.WriteLine("Bar");
return 0;
}
}

class Test
{
static void Main()
{
Foo f = new Foo();
Bar b = new Bar();
}
}




Answer: On my box, Bar is printed and then Foo. This is because Foo has a static constructor, which cannot be run until the exact point at which the class first has to be initialized. Bar doesn't have a static constructor though, so the CLR is allowed to initialize it earlier. However, there's nothing to guarantee that Bar will be printed at all. No static fields have been referenced, so in theory the CLR doesn't have to initialize it at all in our example.