Static field initialization order (C #) - can someone explain this fragment?

I am a C ++ programmer learning C #. I am currently reading C # 4.0 in a nutshell.

I came to this statement / snipet on page 74:

Static field initializers are launched in the order in which the fields are declared. The following example illustrates this: X initializes to 0 and Y initializes to 3.

class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}

I do not understand how X can be assigned a value in Y, without the first declaration. Did I miss something?

As well as a side, based on the background in C ++, I usually use the term ctor for the constructor - however, I have not come by comparison with the term in C # - is this the ctor term also used in the C # world?

[change]

The following example on the same page (in the previous book):

class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}

The book states (for the example above):

0, 3 , Foo X 3:

.

  • , , ctor - , , . , ctor , , "static". , . ?

  • () ctor X, 3 , - 0. ?!

+5
6

# , int, . int 0. ++, , . Y, , int, X 0.

ctor, , #, . , Visual Studio, , .

+5

, . , , . - , , , ..

, . , const, 3 - , - ( ). , , IL.

, .., .

- "" "ctor", , . , :

var ctor = typeof(...).GetConstructor(...);
+7

.

Y , Y.

, , :

  • X , Y, , , 0 ( int)
  • Y 3.
+2

. , , . Y X.

, :

class Foo {

  public static int X; // 0
  public static int Y; // 0

  static Foo() {
    X = Y; // 0
    Y = 3; // 3
  }

}

( , , , , . , .)

"ctor" "" #, , , .NET. , , StringComparison.CurrentCultureIgnoreCase, - str_cmp.cc_is.

"ctor" Visual Studio, "ctor" , .

+1

, :

   class Foo
    {
        public static int y1 = 3;
        public static int x1 = y1;

        public static int X = Y; // 0
        public static int Y = 3; // 3


    }

,

        public static int y1 = 3;
00000021  mov         dword ptr ds:[009E9360h],3 
        public static int x1 = y1;
0000002b  mov         eax,dword ptr ds:[009E9360h] 
00000030  mov         dword ptr ds:[009E9364h],eax 

        public static int X = Y; // 0
00000035  mov         eax,dword ptr ds:[009E936Ch] 
0000003a  mov         dword ptr ds:[009E9368h],eax 
        public static int Y = 3; // 3
0000003f  mov         dword ptr ds:[009E936Ch],3 

Y , 0.

0

, , , , , . :

class MyClass
{
    public void MyMethod()
    {
        var a = field1;
    }

    int field1;        
}

1 MyMethod, , ( ) .
.

0

All Articles