Reputation: 5326
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()
//{
//}
}
Upvotes: 0
Views: 680
Reputation: 156948
That is because this line is ran before the static
constructor:
public static B b = new B();
Your first line in the static
constructor (the part you don't see, but is actually there) is actually calling the constructor of B
. That is the reason you don't see the static
constructor hit first.
If you would write it like this, you would see the static
constructor hit first:
static B()
{
Console.WriteLine("THis is staticcc");
b = new B();
}
public static B b;
Upvotes: 1
Reputation: 1500065
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
Upvotes: 5