Consider this code example:
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 as follows:
public static void Main() { new B(); Console.WriteLine(B.TheT); }
B.TheT is a "Test" as expected. I can understand that this forces the static constructor to run, but why does this not happen in the first case?
I tried to read the specification and it caught my attention (§10.12):
[...] The execution of the static constructor is started first of the following events to occur in the application domain:
• [...]
• Any of the static members of the class type are specified.
My interpretation of this is that since TheT not a member of B , the static constructor of B does not start. Is it correct?
If this is correct, what would be the best way to let B specify how to initialize TheT ?
source share