How to run a static initialization method in C # before the Main () method?

Given a static class using the initializer method:

public static class Foo { // Class members... internal static init() { // Do some initialization... } } 

How can I make sure that the initializer is started 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 any unforeseen reservations? And is there a better way to do this?

+8
c # static-methods static-classes
source share
3 answers

Just initialize inside the static constructor for Foo .

From the documentation:

The static constructor is called automatically to initialize the class before creating the first instance or any static link members.

+10
source share

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... } } 
+3
source share

Move the code from the internal static method to the static constructor as follows:

 public static class Foo { // Class members... static Foo() { // Do some initialization... } } 

Thus, you are absolutely sure that the static constructor will be launched at the first mention of your Foo class, whether it be building an instance or accessing a static member.

+2
source share

All Articles