Home > OS >  Static member initialize order when an object of a derived class is created
Static member initialize order when an object of a derived class is created

Time:07-08

I'm practicing the member initialize order when an object is created.

I know the order this:

  1. static variable 0 initialize
  2. static variable initialize syntax
  3. base class static constructor
  4. static constructor
  5. instance variable 0 initialize
  6. instance variable initialize syntax
  7. base class instance constructor
  8. instance constructor

Am I taught correctly?

And here is the code I tested:

 public class Person
 {
1  public static int PersonAge = Man.ManAge;
 
   static Person()
   {
2    Man.ManAge  ;
3    Console.WriteLine($"Person : {PersonAge}");
   }
  }
   
  public class Man : Person
  {
4   public static int ManAge = 2;
  
    static Man()
    {
5     Console.WriteLine($"Man : {ManAge}");
    }
  }
var man = new Man();

I was expecting the following execution result:

Person : 3
Man : 3

But, the result is:

Man : 2
Person : 2

I think you have to 1 → 4 → 5 → 2 → 3 in order to proceed as the reuslt.

But, as I have learned, 4 → 2 → 1 → 3 → 5.

What am I doing wrong?

CodePudding user response:

The order of static constructor call is the opposite of the order of instance constructor call, check this for details :

Static default constructor execution order is from bottom to top (child to parent). And, Non-Static default constructor execution order is from top to bottom (parent to child).

Thus, you have Man static initialization then Man static ctor, then static Person Initialization then Person's static ctor. and you get : 4 → 5 → 1 → 2 → 3.

  • Related