I was just reading Inheritance in C# in which i came across the Constructors and was written that constructors are executed in order of derivation. What does it mean?That base class constructor will be called first or Derived class.
The base class constructor will be called first. You can test this pretty easily yourself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DerivationTest
{
class Program
{
public class Thing
{
public Thing()
{
Console.WriteLine("Thing");
}
}
public class ThingChild : Thing
{
public ThingChild()
{
Console.WriteLine("ThingChild");
}
}
static void Main(string[] args)
{
var tc = new ThingChild();
Console.ReadLine();
}
}
}
A base class Constructor is called first.Refer to the following example
// Demonstrate when constructors are called.
using System;
// Create a base class.
class A {
public A() {
Console.WriteLine("Constructing A.");
}
}
// Create a class derived from A.
class B : A {
public B() {
Console.WriteLine("Constructing B.");
}
}
// Create a class derived from B.
class C : B {
public C() {
Console.WriteLine("Constructing C.");
}
}
class OrderOfConstruction {
static void Main() {
C c = new C();
}
}
The output from this program is shown here:
Constructing A.
Constructing B.
Constructing C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With