A brief analysis of the sequence of initialization of c constructs

  • 2020-05-19 05:33:44
  • OfStack

This is very basic knowledge, but I have not realized it until now. It's a failure to think about it.

Directly on the code: very simple


public class Base
    {
        int i=0;
        public Base()
        {
            System.Console.WriteLine(" I'm the base class constructor ");
        }

    }
 class Program
    {
        static void Main(string[] args)
        {
            Base d = new Base();
        }
    }

For the code above. Do you want to execute the constructor first, or do you want to initialize the field i variable first? In fact, once you realize this problem, it is easy to try it out. It should be the field i variable that is first enabled.

Now, if Base derives a subclass, what is the order in which it is constructed?


/// <summary>
    ///  The base class 
    /// </summary>
    public class Base
    {
       public int baseint = 100;
        public Base()
        {
            System.Console.WriteLine(" Constructor: I am the base class constructor ");

        }
        private class Inner
        {
            public Inner()
            {
                System.Console.WriteLine(" Field: I am a base class Inner");
            }
        }
        /// <summary>
        ///  Field initialization 
        /// </summary>
        private Inner inner = new Inner();
    }

   /// <summary>
   ///  A subclass 
   /// </summary>
    class Derived : Base
    {
       
        public Derived()
        {
            System.Console.WriteLine(" Constructor: I'm a subclass constructor ");

        }

       private class Inner
        {
            public Inner()
            {
                System.Console.WriteLine(" Field: I'm a subclass Inner");
            }
        }
        /// <summary>
        ///  Field initialization 
        /// </summary>
        private Inner inner = new Inner();
    }

So the order of execution is: subclass field - superclass field - superclass constructor - subclass constructor


Related articles: