Consider this example code:
public class A<T>
{
public static T TheT { get; set; }
}
public class B : A<string>
{
static B() {
TheT = "Test";
}
}
public class Program {
public static void Main(String[] args) {
Console.WriteLine(B.TheT);
}
}
Here B.TheT is null. However, changing the Main method like this:
public static void Main() {
new B();
Console.WriteLine(B.TheT);
}
B.TheT is “Test”, as expected. I can understand that this forces the static constructor to run, but why does this not happen for the first case?
I tried reading the spec, and this caught my attention (§10.12):
[…] The execution of a static constructor is triggered by the first of the
following events to occur within an application domain:• […]
• Any of the static members of the class type are referenced.
My interpretation of this is that since TheT is not a member of B, the static constructor of B is not forced to be run. Is this correct?
If that is correct, how would I best let B specify how to initialize TheT?
Basically, you haven’t really referenced
B. If you look in the IL, I think you’ll find that your code was actually equivalent to:The compiler worked out that that’s really the member you meant, even though you wrote
B.TheT.I would try to avoid doing this to start with, to be honest… but you could always just add a static method to
B: