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?
You can't do it with attributes (without extra code), but you can force type initialization with reflection.
For example:
foreach (Type type in assembly.GetTypes())
{
ConstructorInfo ci = type.TypeInitializer;
if (ci != null)
{
ci.Invoke(null);
}
}
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:
foreach (Type type in assembly.GetTypes())
{
if (type.GetCustomAttributes(typeof(..., false)).Length == 0)
{
continue;
}
ConstructorInfo ci = type.TypeInitializer;
if (ci != null)
{
ci.Invoke(null, null);
}
}
You could do this with LINQ, admittedly:
var initializers = from type in assembly.GetTypes()
let initializer = type.TypeInitializer
where initializer != null &&
type.GetCustomAttributes(typeof(..., false).Length > 0
select initializer;
foreach (ConstructorInfo initializer in initializers)
{
initializer.Invoke(null, null);
}
Simply reference a static field on that type at the beginning of your application. There's no way of doing this solely by altering the code at the class definition site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With