Click here to Skip to main content
15,893,644 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public class child:parent
    {
        public child()
        {
            System.Windows.Forms.MessageBox.Show("child ns");
        }
        static child()
        {
            System.Windows.Forms.MessageBox.Show("child s");
        }

    }
    public class parent
    {
        public parent()
        {
            System.Windows.Forms.MessageBox.Show("parent ns");
        }
        static parent()
        {
            System.Windows.Forms.MessageBox.Show("parent s");
        }
    }


I have this code and when i make object of the child class... The order of execution of constructor is child static,parent static,parent non static and child non static... All i want to know is the reason for this...
Thanks...
Posted

1 solution

Static has to precede non-static - otherwise the non-static constructor could not rely on (or even access!) static elements of the class. So all static construction needs to precede all non-static.

Child construction must follow parent in non-static classes, so that child instances can rely on parent properties. In actual fact, the constructor for the child is called first - this triggers the parent constructor before any child code is executed.

The only one which looks odd is the child-first static, which is actually following the same order as the public: child constructor first, but the parent constructor is called the first time it is needed - so if you change your code slightly:
C#
public class child : parent
    {
    public child()
        {
        Console.WriteLine("child ns");
        }
    static child()
        {
        Console.WriteLine("child s");
        X = "goodbye";
        Console.WriteLine("child s end");
        }

    }
public class parent
    {
    public static string X = "hello";
    public parent()
        {
        Console.WriteLine("parent ns");
        }
    static parent()
        {
        Console.WriteLine("parent s");
        }
You will get:
child s
parent s
child s end
parent ns
child ns
Because the parent static constructor is called when the child references a parent static property, or at the end of the child constructor if it hasn't been needed before then. Remember, Static constructors are called once, the first time a static property or method is referenced.

[edit]Typo: "public" instead of "parent" and a spare "the" - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
Rahul_Patel 31-Mar-12 11:32am    
thnks sir.... 5....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900