As we know that base constructor invoked first when we create an instance of child class. But if we create an instance of child class by parameterized constructor and base class has both default and parameterized constructor then which constructor of the base will be invoked first?
When you create an instance of a child class using a parameterized constructor, and the base class has both a default (parameterless) constructor and a parameterized constructor, the default constructor of the base class will be invoked first. This is because the default constructor is automatically called unless you explicitly use the base keyword to call a specific constructor of the base class.
Here's an example to illustrate this scenario in C#:
using System;
class Animal
{
public Animal()
{
Console.WriteLine("Base class default constructor");
}
public Animal(string type)
{
Console.WriteLine($"Base class parameterized constructor with type: {type}");
}
}
class Dog : Animal
{
public Dog(string name) : base("Dog")
{
Console.WriteLine($"Child class constructor with name: {name}");
}
}
class Program
{
static void Main(string[] args)
{
Dog myDog = new Dog("Buddy");
}
}
Output:
Base class default constructor
Child class constructor with name: Buddy
In this example, even though the 'Dog' class's constructor calls the parameterized constructor of the 'Animal' base class using 'base("Dog")', the default constructor of the 'Animal' base class is invoked first. If you want to explicitly call a specific constructor of the base class, you would use the 'base' keyword with the appropriate arguments, as shown in the example.