Search code examples
c#static-constructor

Do both of these constructors do the same thing?


Do both of these code blocks do the same thing?

class A {
   public static int s;
   A(){}
   static A(){s = 100;}
}

and

class A {
   public static int s=100;
   A(){}
   //static A(){s = 100;} do not use
}

Do they do the same thing? I think so.


Solution

  • No, they don't behave quite the same way. Without the static constructor, the timing of exactly when the type initializer executes is much looser - it can happen earlier or later than you'd expect.

    When there's a static constructor, the type initializer executes when the type is first used in terms of any static member being accessed or any instance being created.

    When there isn't a static constructor, the only guarantee is that the initializer will be executed at some point before the first access of a static field (and still exactly once). Depending on the JIT, that might mean it's executed very early (e.g. when you first execute a method which might use a member) or very late (after calling static members which don't use any fields, or after creating and using an instance).

    In IL, the difference is that a type without a static constructor has the beforefieldinit flag; one with a static constructor doesn't.