Let there are two code fragments:
A:
public class Foo
{
private static Bar _unused = new Bar();
}
IN:
public class Foo
{
private static Bar _unused;
static Foo()
{
_unused = new Bar();
}
}
In case A, the CLR does not even call Bar ctor (unless it is debugged or the debugger is connected), but in case B it is called in all circumstances.
The fact is that there can be calls in the Bar constructor that will make this instance accessible from another place - usually these are event subscriptions.
So:
- Why are the values of A and B evaluated differently?
- Why doesn't the CLR call Bar ctor at all in case A - since it should not be evaluated as garbage until ctor is complete and the instance is assigned to the corresponding field?