When static variable is allocated i.e. when you declare class or at the time of object creation?
4 Answers
It is compiled into the static constructor. So the first time anyone creates an object of the class or calls a static method or property on it, the initialization occurs.
Edit: when it is important to you if initialization happens before of after your own static constructor code (and some other edge cases),check the link in the comment by divo.
4 Comments
As other answers have indicated, this will happen in the type (static) constuctor. If your class does not have a type constructor explicitly defined then the compiler will generate one for you. However, determining exactly when this constructor is called is a bit more involved.
If your class does not define an explicit type constructor, e.g.
public class Foo
{
public static int Bar = 1;
}
then the C# compiler will generate a constructor and emit the class definition with the beforefieldinit flag. This will cause the JIT compiler to guarantee that the type constructor is called sometime before a member of the type is first used but this time is non-deterministic, i.e. it is not possible to know exactly when this will happen, and it could be at a much earlier point than when a type member is first used.
If your class declares an explicit type constructor, e.g.
public class Foo
{
public static int Bar;
static Foo()
{
Bar = 1;
}
}
then the compiler will emit IL for the class without the beforefieldinit flag. In this case the JIT compiler will call the type constructor at a deterministic time, i.e. immediately before the first type member access.
The former JIT behaviour is known as before-field-init semantics and the latter as precise sematntics. It is important to know the difference between the two since, in some scenarios, they may have a significant performance implication.
2 Comments
beforefieldinit is whether or not a static constructor exists at all, not whether your fields are initialised inside the constructor. If the class has no static constructor then it will be marked as beforefieldinit by the compiler; if the class has a static constructor then it won't be marked as beforefieldinit, regardless of where its fields are initialised.Static variables are allocated as soon as static (type) constructor is called. This happens when you call any method that reference the type for the first time, before method execution.
3 Comments
beforefieldinit flag meaning the time when the type initializer is executed is not deterministic.