Require all base class static constructors to run when calling a static function on a class #9488
Unanswered
cdaley0
asked this question in
Language Ideas
Replies: 1 comment 2 replies
-
We would not be able to do this. It would certainly break code that doesn't expect these static constructors to run until actually needed. The OP also doesn't seem to give a good reason for why this would be desirable. THe way things work now is that this code is run when needed, and the cost (and other impacts) of those constructors isn't paid until that point. Forcing extra work to be done runs counter to the desires/designs of the rest of the critical code that is executing (especially at important times like app loading). |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Consider the following code
The output of this program when compiled and run on my computer and on .NET Lab is
The static constructor for class B is not being run. At first I thought this was a bug, but in the static constructors guide the following wording is used when describing static initialization: "...Any static constructors, from the ultimate base class of Object.Object through each base class through the type run. The order of static constructor execution isn't specified. However, all static constructors in the hierarchy run before any instances are created."
The wording specifies only that static constructors in the type's hierarchy are run before any instances of the type are created, so it appears that the output above is technically correct because no instances of class C have been created. If
Func2
is changed to be an instance method and invoked vianew C().Func2()
then the static constructor for B is also run.This behavior is counterintuitive. To have a class with two base types in its hierarchy and have the static constructor for the middle type skipped is quite confusing, even if technically allowed according to the language spec. I believe it would be a good idea to update the language so that all static constructors in the hierarchy run before any instances are created, or static functions/fields accessed. I don't know if this would cause any issues when it comes to multiple types inheriting from the same type.
Beta Was this translation helpful? Give feedback.
All reactions