tags:

views:

213

answers:

3

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? [Eric Lippert, where are you???]

  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?

+1  A: 

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.

Maximilian Mayerl
A: 

If you have static constructors or singleton classes which you can access true a static variable C# compiler will emit .cctor.

Shamika
It emits a .cctor in the class where you defined a static constructor, yes, but that is just the static constructor of that class and will run the first time the class is accessed. A module initializer is a .cctor on the pseudo <Module> class and is guaranteed to run before ANY other code in the assembly, regardless of what code is accessed first.
Einar Egilsson
A: 

Here is a link that might help you: http://tech.einaregilsson.com/2009/12/16/module-initializers-in-csharp/

Nils
Hehe, that is my own page that I actually linked to in the question itself. But thanks ;)
Einar Egilsson