Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force construction of static objects

Tags:

c#

.net

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?

like image 693
kyku Avatar asked May 16 '26 19:05

kyku


2 Answers

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);
}
like image 160
Jon Skeet Avatar answered May 18 '26 09:05

Jon Skeet


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.

like image 27
mmx Avatar answered May 18 '26 07:05

mmx