Why isn't the static constructor hit first?

I have the below code and I have only two simple questions which are normal to expect in the behavior of the program below, which I am not seeing unfortunately:

  1. Static constructor in any class should be the first one to be hit soon after static fields being hit. Then only instance constructor. But what I am seeing is, the debug first goes to the public constructor. Sad thing. Why?

Although: the output of the program is:

This is Staticcc...

1

...Which is correct.

  1. I kept a break point in the Static constructor start, but when I debug it only shows break point in the end brace of static constructor. Why?

Sample code:

public sealed class B  : A, C
{
    public   int? m = 0;
    public B()
    {
        m = 1;
    }
    private B(int a, int b)
    {
        m = 2;
    }
    protected B(int x, int y, int z)
    {
        m = 3;
    }       

    static B()
    {
        Console.WriteLine("THis is staticcc");
    }

    public static B b = new B();
    public static B BC
    {
        get
        {
            return b;
        }
    }

    static void Main()
    {           
        Console.WriteLine(B.BC.m);
        Console.ReadKey();
    }
}

public interface C
{
}

public  class A 
{
    //private A()
    //{

    //}       
}
Jon Skeet
people
quotationmark

This is the problem:

public static B b = new B();

Static field initializers are executed before the static constructor is executed. From the C# spec section 10.5.5.1:

If a static constructor (10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor.

Your static field initializer calls your instance constructor, therefore the instance constructor is the first thing to execute.

Although: the output of the program is This is Staticcc... then 1...Which is correct.

Yes, because all of the initialization happens as part of evaluating B.BC.m in Main.

If you add Console.WriteLine("Instance Constructor"); into your constructor, you'll see:

Instance Constructor
THis is staticcc
1

If that doesn't help, think of Main as being this:

int tmp = B.BC.m;       // This prints initialization bits
Console.WriteLine(tmp); // This prints 1

people

See more on this question at Stackoverflow