I'm designing a domain-specific CLI, and for the last couple weeks I've been investigating various corner cases to make sure I have a firm understanding of what's required.
Right now I'm looking into type construction. I'm considering the following scenario, which I can't find much information on:
class C
{
public static int Field = D.Field;
}
class D
{
public static int Field = C.Field;
}
class TestProg
{
static void Main()
{
Console.WriteLine( D.Field );
}
}
Both of the classes are marked beforefieldinit
.
Interestingly, this program actually compiles, and runs on the MSCLR, yielding:
0
So it seems what's happening in practice is that the trigger point in C..cctor
to construct D
is ignored because D
's construction has already started. However, to me, this program looks invalid, in the sense that C..cctor
is using something before it is fully constructed.
Many will point out that the above scenario is pointless, but it is a concern to me as an implementor of the CLI because I need to know how much latitude I have with regard to circular-references in type initializers.
All I can find in ECMA-335 about this is:
If marked BeforeFieldInit then the type’s initializer method is executed at, or sometime before, first access to any static field defined for that type.
The words "executed at" leave some ambiguity in this case because they don't specify whether the entire initializer has to execute or whether execution has to simply begin.
I ran into a comment alluding to specific rules in the CLI specs about the circular reference case, but so far I have not been able to find any mention of the issue at all in ECMA-335.
So, my questions are:
Is the above program relying on undefined behaviour? Or unspecified behaviour?
If my CLR refused to load the above program, would it still be compliant?
If not, what are the exact rules about circular references in type constructors?
Are there any valid, useful design patterns that could lead to cycles in the directed graph of a program's type initializers when flow control is discounted?