Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module initializers in C#

Module initializers are a feature of the CLR that are not directly available in C# or VB.NET. They are global static methods named .cctor that are guaranteed to run before any other code (type initializers, static constructors) in an assembly are executed. I recently wanted to use this in a project and hacked together my own solution (console program/msbuild task) using Mono.Cecil, but I was wondering:

  1. Is there any way to trick the C# compiler into emitting module intializers? Any attributes (e.g. CompilerGenerated, SpecialName) or other trickery that could be used?

  2. Do the C# / VB.NET ever emit these initializers themselves for some purpose? From what I've seen they are used by managed C++ for some interop purposes, but I couldn't find any reference to them being used for other purposes. Any ideas?

like image 457
Einar Egilsson Avatar asked Dec 16 '09 15:12

Einar Egilsson


4 Answers

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();
}
like image 153
David Roth Avatar answered Oct 19 '22 00:10

David Roth


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.

like image 21
Maximilian Mayerl Avatar answered Oct 19 '22 01:10

Maximilian Mayerl


After eleven years, this is finally supported by the language in C#9

https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#support-for-code-generators

like image 8
Carlos Araujo Avatar answered Oct 19 '22 01:10

Carlos Araujo


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

like image 3
Nikolay Avatar answered Oct 19 '22 00:10

Nikolay