Static time distribution of variables in .net

When is a static variable assigned, that is, when do you declare a class or when creating an object?

+3
source share
4 answers

It is compiled into a static constructor. Therefore, the first time someone creates an object of a class or calls a static method or property on it, initialization occurs.

Edit: if it is important for you if initialization happens earlier than after your own static constructor code (and some other cases with an edge), check the link in the divo comment.

+6
source

upon first access to the class.

+4
source

, () constuctor. , . , , , .

,

public class Foo
{
    public static int Bar = 1;
}

# beforefieldinit. JIT , - , , , .. , , , .

,

public class Foo
{
    public static int Bar;
    static Foo()
    {
        Bar = 1;
    }
}

IL beforefieldinit. JIT , .

The previous JIT behavior is known as before-field-init semantics, and the second is known as exact semantics. It is important to know the difference between the two, since in some scenarios they can have significant performance.

+2
source

Static variables are allocated as soon as the static (type) constructor is called. This happens when you call any method that references the type for the first time before executing the method.

0
source

Source: https://habr.com/ru/post/1726252/


All Articles