Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 892
Person.Junkie Avatar asked Dec 01 '22 15:12

Person.Junkie


2 Answers

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.

like image 162
Jon Skeet Avatar answered Dec 04 '22 03:12

Jon Skeet


The effect is the same, but the actual order of execution may be different. When there is a static constructor, static fields are initialized immediately before the constructor is called or any of the static fields are accessed. If there is no static constructor, then the field initializers can be executed at any time prior to the first usage of one of the static fields.

Since your initializers have no side-effects and cannot throw exceptions, there would not be any discernable difference in the two, barring the use of reflection or some other outside observer (e.g. debugger)

like image 29
D Stanley Avatar answered Dec 04 '22 03:12

D Stanley