As I’ve learned the static objects in classes are constructed when the class is being referenced for the first time. However I’d find it sometimes usefull to initialize the statics when the program is being started. Is there some method (ie by using annotations) of enforcing it?
Share
You can’t do it with attributes (without extra code), but you can force type initialization with reflection.
For example:
Note that this won’t invoke type initializers for generic types, because you’d need to specify the type arguments. You should also note that it will force the type initializer to be run even if it’s been run already which flies in the face of normal experience. I would suggest that if you really need to do this (and I’d try to change your design so you don’t need it if possible) you should create your own attribute, and change the code to something like:
You could do this with LINQ, admittedly: