Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a static initializer method in C# before the Main() method?

Tags:

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?

like image 700
Matt Avatar asked Nov 29 '12 09:11

Matt


Video Answer


2 Answers

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.

like image 157
Jon Avatar answered Sep 27 '22 20:09

Jon


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...     } } 
like image 32
João Simões Avatar answered Sep 27 '22 22:09

João Simões