24

Given a static class with an initializer method:

public static class Foo
{
    // Class members...

    internal static init()
    {
        // Do some initialization...
    }
}

How can I ensure the initializer is run before Main()?

The best I can think of is to add this to Foo:

private class Initializer
{
    private static bool isDone = false;
    public Initializer()
    {
        if (!isDone)
        {
            init();
            isDone = true;
        }
    }
}

private static readonly Initializer initializer = new Initializer();

Will this work or are there some unforeseen caveats? And is there any better way of doing this?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Matt
  • 21,026
  • 18
  • 63
  • 115

4 Answers4

26

Simply do the initialization inside a static constructor for Foo.

From the documentation:

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

John Cummings
  • 1,949
  • 3
  • 22
  • 38
Jon
  • 428,835
  • 81
  • 738
  • 806
14

There are static constructors in C# that you can use.

public static class Foo
{
    // Class members...

    static Foo(){
        init();
        // other stuff
    }

    internal static init()
    {
        // Do some initialization...
    }
}
John Cummings
  • 1,949
  • 3
  • 22
  • 38
João Simões
  • 1,351
  • 1
  • 10
  • 20
7

Move your code from an internal static method to a static constructor, like this:

public static class Foo
{
  // Class members...

  static Foo()
  {
    // Do some initialization...
  }
}

This way, you are quite sure that the static constructor will be run on first mention of your Foo class, whether it's a construction of an instance or access to a static member.

Pang
  • 9,564
  • 146
  • 81
  • 122
SWeko
  • 30,434
  • 10
  • 71
  • 106
4

Place your initialization code in the static constructor of the class

static Foo()
{
    // Initialization code
}

This constructor is run the first time the class is accessed.

You can use RunClassConstructor to trigger the static constructor of the class before using a class. This can be useful if, for instance, this class registers itself in a IOC container or something like this.

RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);

You find the RuntimeHelpers in the System.Runtime.CompilerServices namespace.


C# 9.0 added Module Initializers allowing you to write initialization code for the assembly with no need to explicitly call anything.

Apply the [ModuleInitializer] attribute to a static void parameterless method to make it a module initializer.

[ModuleInitializer]
internal static void MyAssemblyInitializer()
{
    // ...
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188