Why aren't all static constructors called in C# (i.e. those of the parent classes)?

﹥>﹥吖頭↗ 提交于 2019-12-04 05:48:39

A static constructor is called when (according to TCPL):

  • An instance of the class type is created.
  • Any of the static members of the class type are referenced.

As an example, consider a class with the static Main method in which execution begins: if you have a static constructor, it will be called before the Main method is called.

Note that even before a static constructor is executed, any static fields are initialized to their default value and then the static field initializers are executed for those field. Only then, the static constructor (cctor) is executed.


To answer your question more directly: static constructors are not inherited, and they cannot be called directly, hence your Base cctor will not be called in your scenario, unless you give the abstract Base class a static method and call that first, i.e. as in Base.Initialize(), as you already suggested.

About the reasoning, that's simple, thinking C# (in Java this is different): static methods are not inherited, thus static constructors should neither be inherited as this could cause unwanted side effects (a cctor called when nothing references that class).

Static methods belong to the class and there is no inheritance. The fact that you can call Final.Setup is just a syntactic sugar for calling Derived.Setup, so no static member of Final has been referenced - therefore the static constructor is not called. Same for Base class - there is no inheritance on static members, so the Base class is not involved in any way here.

The C# rules dictate that static constructors are called before the first instance of the class is created or any static member is touched, ergo, possibly never, as in your case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!