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:
Although: the output of the program is:
This is Staticcc...
1
...Which is correct.
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()
//{
//}
}
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
See more on this question at Stackoverflow