Module initializers in C#

Check out the module initializer addon of the awesome opensource IL-Weaver project "fody", written by Simon Cropp: https://github.com/fody/moduleinit

It allows you to specify a method which will be translated into an assembly initializer by fody:

public static class ModuleInitializer
{
    public static void Initialize()
    {
        //Init code
    }
}

gets this:

static <Module>()
{
    ModuleInitializer.Initialize();
}

No, there is no way to emit them in C#, because C# puts everything in a class/struct and module initializers need to be global.

You will have to use a different tool to write them, preferably IL-Assembler.

As for the second question, I have to admit that I don't know, but I have never seen any generated by C#, and I use ILDasm quite often, so I assume that it doesn't emit them.


Maybe System.Reflection.Emit namespace can help you. MethodAttributes enumeration contains similar elements (SpecialName, RTSpecialName).