Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable order [duplicate]

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?

like image 531
user2110292 Avatar asked Mar 13 '13 14:03

user2110292


2 Answers

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.

like image 102
Thomas Levesque Avatar answered Sep 22 '22 16:09

Thomas Levesque


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.

like image 31
Botz3000 Avatar answered Sep 19 '22 16:09

Botz3000