Tuesday, January 26, 2021

C# 9–Module Initializer

Yesterday I blogged about an issue I had with Telerik. I needed to initialize some code before I could call the PDF conversion functionality:

The question is where should I put this logic?

Perfect case to try out a new C# 9 feature: Module initializers.

Module initializers allow you to do eager, one-time initialization when a module is loaded, with minimal overhead and without the user needing to explicitly call anything.

Creating a module initializer is easy. Just add the ModuleInitializerAttribute on top of a method. Some requirements are imposed on the method targeted with this attribute:

  1. The method must be static.
  2. The method must be parameterless.
  3. The method must return void.
  4. The method must not be generic or be contained in a generic type.
  5. The method must be accessible from the containing module.