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:
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?
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?
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
Module initializers are methods that have the
ModuleInitializerAttribute
attribute attached to them. These methods will be called by the runtime before any other field access or method invocation within the entire module. A module initializer method:
Must be static
Must be parameterless
Must return void
Must not be a generic method
Must not be contained in a generic class
Must be accessible from the containing module
That last bullet point effectively means the method and its containing class must be internal or public. The method can't be a local function. For more information, see ModuleInitializer attribute.