Reputation: 899
I have a base class and derived class. If I'm creating an object of the derived class, which constructor will be taken first: the base constructor or the derived constructor?
Upvotes: 0
Views: 325
Reputation: 3931
The instance constructors are initialize in reverse order. The base constructor will be initialized first, then the derived constructor.
Take a look here http://www.csharp411.com/c-object-initialization/
There is a good overview of the order in which the object's fields and constructors are initialized:
Upvotes: 4
Reputation: 9209
The base class constructor will be processed first, followed by each derived constructor.
*edit added the following code * You can see this by creating a ClassOne object and using the debug "Step Into" on the following:
class BaseClass
{
public BaseClass(int num)
{
this.fieldNumber = num;
}
private int fieldNumber;
}
class ClassOne : BaseClass
{
public ClassOne(int num1, int num2): base(num1)
{
this.fieldNumber = num2;
}
private int fieldNumber;
}
Upvotes: 0
Reputation: 3073
Taking the question at face value (i.e. with no code), then, the base class constructor runs first. This way the base class can be initialised first - the derived class may depend on objects in the base class being initialised .
If there are two or more levels of inheritance then the least specialised constructor is called first.
Upvotes: 2
Reputation: 700372
The base class constructor will be called first.
For example, if you have these classes:
public class A {
public A() {
Console.WriteLine("a");
}
}
public class B : A {
public B() {
Console.WriteLine("b");
}
}
If you create an instance of the class B
, it will first output "a", then "b".
Upvotes: 0
Reputation: 31222
Assuming your code is like this:
class Foo
{
public Foo()
{}
}
class Bar : Foo
{
public Bar() : base()
{}
}
then calling the constructor of Bar
will run the constructor of Foo
first.
Upvotes: 0
Reputation: 1038900
Base constructor is called first. That's easy to verify:
class Program
{
class Base
{
public Base()
{
Console.WriteLine("base ctor");
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine("derived ctor");
}
}
static void Main()
{
new Derived();
}
}
Upvotes: 3
Reputation: 55489
The base constructor will be called first.
try it:
public class MyBase
{
public MyBase()
{
Console.WriteLine("MyBase");
}
}
public class MyDerived : MyBase
{
public MyDerived():base()
{
Console.WriteLine("MyDerived");
}
}
Check this link too for details - http://www.csharp-station.com/Tutorials/lesson08.aspx
Upvotes: 1
Reputation: 11397
first called the base class
constructor
class Base
{
public Base()
{
Console.WriteLine("Base");
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine("Derived");
}
}
class Program
{
static void Main()
{
Derived d = new Derived();
}
}
output will be
Base
Derived
Upvotes: 2