Order of calling constructors(in C#)
Explanation:
Constructor works differently in Inheritance little bit confusing for new Programmers. There are two notions in execution of constructor.
1. Calling
2. Execution
When you create an object of your derived class Named Derived the constructor first goes to Derived() then it goes to Parent() because of its calling. Constructor calling is made from Bottom to Top.
But then you find it Executes Parent() first then Derived, that is because of its Execution. Constructors Executed from Top to Bottom. That's why it print Parent first then Base while base constructor called first.
using System;
namespace InheritanceDemo {
class Parent {
public Parent() {
Console.WriteLine("Hello From Parent");
}
}
class Derived: Parent {
public Derived() {
Console.WriteLine("Hello from Derived");
}
}
public class OrderOfExecution {
public static void Main(string[] args) {
Derived obj = new Derived();
}
}
}
Output:
Hello From Parent
Hello from Derived