Translate

Sunday, October 6, 2013

Class instantiation execution order (Initialization order)

When you instantiate a class, this is the order in which it takes place
  • Static fields (if not already initialized)
  • Static constructor (if not already called)
  • Instance fields
  • Parent class static field (if not already initialized)
  • Parent class static constructor (if not already called)
  • Parent class instance field
  • Parent class instance constructor
  • Instance constructor
If you run this line of code, in the green comments you can see the order in which execution takes place

var c = new Child();



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary1
{
    public class Parent
    {
        public int I=0;//Executes 6th
        public static int X=0;//Executes 4th

         static Parent()
         {
             X = 10;//Executes 5th
         }

        public Parent()
        {
           I = 100;//Executes 7th
        }
    }

    public class Child:Parent
    {
        public int J=0;//Executes 3rd
        public static int Y=0;//Executes 1st

        static Child()
        {
            Y = 55;//Executes 2nd
        }

        public Child()
        {
            J = 5;//Executes 8th
        }
       
    }
}



No comments:

Post a Comment

Comments will appear once they have been approved by the moderator