I have aproblem with the order of static variable declaration in C#
When i run this code:
static class Program {
private static int v1 = 15;
private static int v2 = v1;
static void Main(string[] args) {
Console.WriteLine("v2 = "+v2);
}
}
The output is:
v2=15
But when i change the static variable declaration order like this:
static class Program {
private static int v2 = v1;
private static int v1 = 15;
static void Main(string[] args) {
Console.WriteLine("v2 = "+v2);
}
}
The Output is:
v2 = 0
Why this happend?
The static fields are initialized in the same order as the declarations. When you initialize v2
with the value of v1
, v1
is not initialized yet, so its value is 0.
Static variables are initialized in their order of declaration, so when you are assigning v2
in your second example, v1
still has its default value 0
.
I hope you know that doing things like this is a bad idea though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With