Eager initialization with module initializers
There may be a scenario where certain code has to be eagerly executed when the module is initialized. Though this is a niche scenario, it becomes quite difficult to achieve if we have such a requirement. With the introduction of module initializers in C# 9.0, this is quite easy to achieve.
To run any code at module initialization, we can just mark the method with the ModuleInitializer attribute, as shown in the following code:
[ModuleInitializer]
internal static void Initialize()
{
Console.WriteLine(“Module Initialization”);
}
The .NET runtime will execute the method that is marked with the ModuleInitializer attribute when the assembly is first loaded.
Here are the requirements of the module initializer method:
- It must be a
staticmethod. - The return type must be
void. - It must not be a generic method.
- It must be a parameter-less method.
- The method must be accessible...