Forcing class load
Asked Answered
M

2

12

Is there a way in C# or .net IL to force a class that has a type initializer (static constructor) to load itself, without accessing any of its parameters?

Assuming I've got the class

public static class LogInitialization {
    static LogInitialization() {
        System.Console.WriteLine("Initialized");
    }
}

Is there a way to get this line to print?

Note that the class is static so I can't instantiate it to force initialization, and it has no public members so I can't access them to start it.

Musketry answered 15/11, 2010 at 5:12 Comment(0)
M
13

Rummaging in the CLI spec, I found a reference to the method RuntimeHelpers.RunClassConstructor

If a language wishes to provide more rigid behavior — e.g., type initialization automatically triggers execution of base class’s initializers, in a top-to-bottom order — then it can do so by either:

  • defining hidden static fields and code in each class constructor that touches the hidden static field of its base class and/or interfaces it implements, or
  • by making explicit calls to System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor (see Partition IV).
Musketry answered 15/11, 2010 at 5:33 Comment(1)
To use this, pass in the result of the TypeHandle property on your instance of Type.Quash
M
7

I usually create a dummy (empty) Init method on classes with static constructors to force the static constructor execution. ie.

public static void Initialize() 
{ 
  // this will force your static constructor to execute, obviously
}

That said, you can always go for the Type.TypeInitializer with reflection... http://msdn.microsoft.com/en-us/library/system.type.typeinitializer.aspx

EDIT: One other thing I've done in the past, is to create an attribute called RequiresInitializationAttribute then on AssemblyLoad scan the assembly for types with such an attribute and using the type.TypeInitializer to force the static constructor to execute when the containing assembly is loaded.

I guess the real question, as usual, is...what are you trying to accomplish?

Manor answered 15/11, 2010 at 5:20 Comment(4)
Yes, I could just call the .cctor myself - I just was not sure if that would preclude the CLR from calling it again.Musketry
Also, calling the type initializer on static types fails! "Cannot create an instance of A because it is an abstract class." I don't see why that message is related, but that's what I get.Musketry
As for what I'm trying to accomplish, I'm basically compiling from a language that has strict rules about when classes should be loaded - so I want to load them at the right times.Musketry
In .net 4 there is a problem you way - look here msmvps.com/blogs/jon_skeet/archive/2010/01/26/…Variometer

© 2022 - 2024 — McMap. All rights reserved.