楼窗晚风

烟霭也似的遐思和怅惘。

Refer to Module Initializer documentation, the ModuleInitializer is a useful attribute, which enable your program run something as it initialized.

Usage of this attribute is very simple, just have a class, and a parameterless static method that returns void, and simply give it an attribute.

using System.Runtime.CompilerServices;

namespace LanguageLab;

public class ToBeInitialized
{
    [ModuleInitializer]
    public static void SayHello()
    {
        Console.WriteLine("Hello!");
    }
}

And then when you run your application, even if there’s no any code in Main method, but the string Hello! will be still printed.

Author : AHpx
This blog is under a CC BY-NC-SA 3.0 Unported License
Link to this article : https://sinoahpx.github.io/2023/01/18/ModuleIntializer-in-CSharp/

This article was last updated on days ago, and the information described in the article may have changed.