C# static class constructor

jM2.me picture jM2.me · Jul 17, 2011 · Viewed 123.5k times · Source

Is there a work around on how to create a constructor for static class?

I need some data to be loaded when the class is initialized but I need one and only one object.

Answer

Jared S picture Jared S · Jul 17, 2011

C# has a static constructor for this purpose.

static class YourClass
{
    static YourClass()
    {
        // perform initialization here
    }
}

From MSDN:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced

MSDN link

.