When do static fields occur?

I am trying to understand when static fields arise and read this MSDN article - http://msdn.microsoft.com/en-us/library/79b3xss3 - but this seems to contradict myself:

First he says:

Static elements are initialized before the static member is available for the first time and before the static constructor is called, if any.

But then he continues:

If your class contains static fields, specify a static constructor that initializes them when the class loads.

So my question is basically this: when are static fields actually initialized and when do they first appear? Is this before calling the static constructor during or after?

Many thanks!

+5
source share
4 answers

The C # language specification states (c 10.5.5.1 Static field initialization):

The initializers of a static variable of a class field correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor exists in the class (§ 10.12), the execution of the initializers of the static field occurs immediately before the execution of this static constructor. Otherwise, the initializers of the static field are executed at an implementation-dependent time until the first use of the static field of this class

, - , , . , , .

, "", , . , , . ( 10.12):

:

. .

. .

+7

"" . , . .

:

  • ""
  • "normal"

:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Start");
        int b = A.B;
        Console.WriteLine("Read A.B");
        new A();
        Console.WriteLine("Built A");
    }
}

class A
{
    public static int B = mystaticfunc();

    static int mystaticfunc() {
        Console.WriteLine("Static field");
        return 1;
    }

    static A()
    {
        Console.WriteLine("Static constructor");
    }

    int C = myfunc();

    static int myfunc()
    {
        Console.WriteLine("Field");
        return 1;
    }

    public A()
    {
        Console.WriteLine("Constructor");
    }
}

:

Start
Static field
Static constructor
Read A.B
Field
Constructor
Built A
+2

.

.

+1

CLR . .

# , , , .

+1

All Articles