Static field initializers in c#
I have following code in c#
class Test
{
public static int X = Y;
public static int Y = 3;
}
static void Main()
{
Console.WriteLine(Test.X);
Console.WriteLine(Test.Y);
}
In this case I am getting 0 and 3 but in the following case I am getting 3,3
class Test
{
public static int X = 3;
public static int Y = X;
}
static void Main()
{
Console.WriteLine(Test.X);
Console.WriteLine(Test.Y)开发者_如何学运维;
}
why is it so?
From the C# spec:
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.
Therefore, in your first snippet, since Y
isn't initialized yet when X
is, X
has to default to 0
(because default(int) == 0
). On the other hand, in your second snippet, Y
can be initialized to the value of X
because X
has already been given a value of 3
in the immediately-preceding statement.
This is per the specification, which states the order for which static fields are initialized. The basic point is that they are initialized in the order that they are declared.
Consequently, in your first snippet, X
is initialized first and then Y
. As Y
has not been initialized yet, it has the default value of 0
and so X
gets the value 0
.
In your second snippet, X
is initialized first but is given the explicit value of 3
. Then, Y
is initialized and is given the value of X
which is 3
since it was initialized first.
From §10.5.5.1 Static field initialization
The static field variable initializers of a class 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 (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor.
Geek -
When you instantiate an int, it's default value is 0. Hence, when you run:
public static int X = Y;
public static int Y = 3;
...the Y is "0" when you set X equal to it, and you are setting Y to 3. But when you run:
public static int X = 3;
public static int Y = X;
You are setting X equal to 3 and THEN setting Y = X (which is now 3).
Fields are initialized in the order of their declaration. In the first case, you initialize X with the value of Y, but Y isn't initialized yet, so its value is 0. In the second case, you initialize Y with the value of X, which is 3, so both fields contain 3.
Simply because the X is declared before Y and is also Initialized in that order. So by default an int is 0 so X was Zero when Y was not initialized.
Correct me if I'm wrong (or downrate me, w/e) but ints are value type in C#. When you first assign X to Y's value, Y is worth 0, and it copies the value, and not the reference.
精彩评论