Raghav55
Raghav55

Reputation: 3135

Initialization of static members

class Test
{
   private static int m = 10;
   private static double n = 20;

   public Test()
   {

   }
}

If a static constructor is used, the static variables are initialized when the first instance of the class is constructed or the first variable is referred. If I don't use a static constructor, when are the static variables initialized and in what order.

Upvotes: 1

Views: 765

Answers (3)

Aliostad
Aliostad

Reputation: 81660

Same place. Compiler spits out the static constructor for you. Order is the one members are defined.


If you look at the class with Reflector, you can see the static constructor:

public class MyStaticClass
{
    public static int MyInt = 10;
}

Becomes:

public class MyStaticClass
{
    // Fields
    public static int MyInt;

    // Methods
    static MyStaticClass();
    public MyStaticClass();
}

With

static MyStaticClass()
{
    MyInt = 10;
}

Upvotes: -1

Cheng Chen
Cheng Chen

Reputation: 43513

In C#4.0, static fields are initialized as lazy as possible without a static constructor.. While in previous versions, we can't give an exact initialization time. Jon Skeet has a great post about this.

Upvotes: 1

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

The C# Language Specification, section 10.4.5.1, says:

If a static constructor exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

So, it's implementation-dependent, but all the static fields are guaranteed to be initialized before one of them is used.

Upvotes: 2

Related Questions