What is the purpose of the <Module> class?

Viewed 131

When decompiling .NET assemblies, I notice that the compiler adds an empty internal class named <Module> on the global namespace. This class is not used from anywhere else in the assembly and its name is an illegal C# identifier.

What is this class and what is its purpose?

1 Answers

According to §II.10.8 of the CLI's Ecma specification, the <Module> class contains the assembly's global fields and methods.

C# does not have such concept, but this class is used by the .NET runtime to support module initializers.

Starting with C# 9.0, module initializers can be defined from code. This snippet:

using System.Runtime.CompilerServices;

public static class C {
    [ModuleInitializer]
    public static void M() {
    }
}

will compile to something like this:

internal class <Module>
{
    static <Module>()
    {
        C.M();
    }
}
public static class C
{
    // On frameworks earlier than .NET 5 you have to define the attribute yourself.
    [ModuleInitializer]
    public static void M()
    {
    }
}

<Module>'s static constructor will be executed once when the assembly gets loaded, and will call all methods decorated with ModuleInitializerAttribute.

As a sidenote, the <Module> class has no ancestor (its BaseType property is set to null); something to keep in mind when using reflection.

Related