BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News C# 9 Proposals: Module Initializers

C# 9 Proposals: Module Initializers

A “module initializer” is a function that is run when an assembly is first loaded. In many ways this is like a static constructor in C#, but rather than applying to one class it applies to the entire assembly.

This feature has existed in the CLR since the beginning, but until now it was not exposed by C#. Under the Module Initializers proposal, this would be exposed as a modification to the static constructor syntax.

[module: ModuleInitializer(typeof(MyModuleInitializer))]
internal static class MyModuleInitializer
{
    static MyModuleInitializer()
    {
        // put your module initializer here
    }
}

As you can see from this example, a module-level attribute is tagged with a class name. That class’s static constructor is then promoted to the module initializer level.

This feature could result in performance gains over normal static constructors. Mark Smeltzer writes,

Currently the runtime takes an init lock which is used to double check whether the static construction logic has been processed. Adding even one static read-only field to a class instantly adds that overhead to every external use of any member of that class.

Having the ability to run initialization logic in a guaranteed, predictable order that has zero post module init runtime performance would be a huge benefit.

Another benefit is a module initializer is predictable; all of the code in it runs sequentially. With static constructors, the order in which they run is non-deterministic from the assembly’s standpoint. Depending on the client code, the constructor for Class A may run before or after Class B.

Terminology notes:

A “module” in the .NET CLR sense is a file containing IL code. An “assembly” is logical unit consisting of one or more modules, one of which is designated as the head assembly. Most .NET languages are designed to only create single-module/single-file assemblies. So, for most developers, the terms are interchangeable.

A “module” in the VB sense is what C# calls a “static class”.

A “satellite assembly” resembles a multi-module/ multi-file assembly in some ways, but it is a separate concept.

Rate this Article

Adoption
Style

BT