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();
}
}
Loading

Akkiraju IvaturiPosted Sep 7, 2012, 11:20 PM
Baris printed and thenFoo. This is becauseFoohas a static constructor, which cannot be run until the exact point at which the class first has to be initialized.Bardoesn't have a static constructor though, so the CLR is allowed to initialize it earlier. However, there's nothing to guarantee thatBarwill 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. This is all due to the beforefieldinit flag.