Calling of Static Constructor and Instance Constructor

前端 未结 3 1098
礼貌的吻别
礼貌的吻别 2021-02-02 03:52

As I know Constructors of parent class is called first and then child Class.But why In Case of static Constructor It executes from derived Class first and then Child Class?

3条回答
  •  难免孤独
    2021-02-02 04:52

    The order in which the static constructors are run is undefined (I think) in your case. The only thing that is guaranteed, is that they will run before instances are created.

    I changed you code into:

        class XyzParent
        {
            protected static int FieldOne;
            protected int FieldTwo;
    
            static XyzParent()
            {
                FieldOne = 1;
                Console.WriteLine("parent static");
            }
            internal XyzParent()
            {
                FieldOne = 10;
                FieldTwo = 20;
                Console.WriteLine("parent instance");
            }
        }
        class XyzChild : XyzParent
        {
            static XyzChild()
            {
                FieldOne = 100;
                Console.WriteLine("child static");
            }
            internal XyzChild()
            {
                FieldOne = 1000;
                FieldTwo = 2000;
                Console.WriteLine("child instance");
            }
        }
    

    Now it matters more which order they run in, for they write to the same field. And with my version of the code, saying new XyzChild(); leads to this output:

    parent static
    child static
    parent instance
    child instance
    

    EDIT: Eric Lippert's answer gives a more precise explanation. The above code only does WriteLine at the end of the static constructors. Add additional WriteLine at the beginning of the static constructors to see that the XyzParent static constructor is run "in the middle" of the execution of the XyzChild static constructor.

提交回复
热议问题