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?
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.
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
Maybe System.Reflection.Emit
namespace can help you. MethodAttributes
enumeration contains similar elements (SpecialName, RTSpecialName)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With