Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Load a static method on class load

Tags:

c#

I have a set of static variables

static string A;
static string B;
static string C;
...

that I would like to initialize.

Now, I could do

static string A;
...
static string Z = InitializeAllVariables();

static void InitializeAllVariables()
{
     /// Initialize all my static variables
}

but that's not very elegant.

Is there a way to force InitializeAllVariables() to run on class load so that I don't need to explicitly call it through a static variable definition?

Thanks.

like image 496
user1836155 Avatar asked Jul 15 '13 20:07

user1836155


1 Answers

Use a static constructor.

public static class MyClass
{
    static string A;
    static string B;
    static string C;

    static MyClass()
    {
        A = "Hello";
        B = "World";
        C = "!";
    }
}
like image 50
John Kraft Avatar answered Oct 17 '22 01:10

John Kraft