Always a parent class constructor is executed before child class' constructor does .. when u instantiate a child/derived class.
Sean Paul
Apr 1st, 2006
Bottom Up, The question is how are they called, not order in which they are they executed. i.e. first the derived class' constructer will be called which in turn will call the parent class' constructor
Ashish
Feb 5th, 2007
It will always be topdown: class a { public a() { Console.WriteLine("Class a"); Console.ReadLine(); } } class b:a { public b() { Console.WriteLine("Class b"); Console.ReadLine(); } } class c : b { public c() { Console.WriteLine("Class c"); Console.ReadLine(); } static void Main(string[] args) { c obj = new c(); } }It will give the result:Class aClass bClass C
A parent class has no reference to the child class, it's the other way around. The code calls the child class, which then calls the parent class, and so on up. Then the constructors are executed top down.
Order of call: From child to parent
Order of execution: From parent to child
Damian
Apr 5th, 2014
Bottomup
Code
using System;
public class A // This is the base class.
{
public A()
{
// Executes some code in the constructor.
Console.WriteLine("Base constructor A()");
}
}
public class B : A // This class derives from the previous class.
{
public B()
{
// The base constructor is called first.
// ... Then this code is executed.
Console.WriteLine("Derived constructor B()");
}
}
class Program
{
staticvoid Main()
{
// Create a new instance of class A, which is the base class.
// ... Then create an instance of B, which executes the base constructor.
var a = new A();
var b = new B();
}
}
Jimuta Bahan Sahu
May 27th, 2014
A) topdown
narendra
Aug 14th, 2014
Code
class Program
{
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("Base class constructor");
Console.ReadLine();
}
}
public class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("Child class constructor");
Console.ReadLine();
}
}
staticvoid Main()
{
ChildClass ch = new ChildClass();
}
}
O/P : Base class constructor
Child class constructor
Sunil
Aug 31st, 2014
TOPDOWN is the correct answer.
Always base class constructor is called before a sub-class constructor gets called.
So, if a class is higher in the class hierarchy, then it will always get called before any sub-class that is lower down in hierarchy.
In sample code below, if we instantiate SClass then automatically the constructor of BClass is called before the SClass constructor. BClass is parent of sub-class SClass, so the higher class constructor gets called first.
In a multilevel hierarchy how are the constructors are called
B) BottomUp
C) None
Related Answered Questions
Related Open Questions