Constructors are class methods which executes when class object is created.
Constructors can be marked as public, private, protected, internal, protected internal, static.
Classes can have multiple constructors. If we do not specify constructor, c# will create default one.
Scenario 1: Inheritance and default constructors
When we inherit base class (Base1) in child class (Base2), and create an object of child class, it executes base class constructor first and child class constructor later. This helps that when child class constructor is executing, system makes sure that base class has already set properties or initializations and then child class can re-set those according to need. Refer below example for this:
class Base1
{
public Base1()
{ Console.WriteLine("Base 1 .ctor called");
}
}
{
public Base1()
{ Console.WriteLine("Base 1 .ctor called");
}
}
class Base2 : Base1
{public Base2()
{ Console.WriteLine("Base 2 .ctor called");
}
}
Actual call is
Base2 base2Obj = new Base2(); or
Base1 base1Obj = new Base2();
Output is
Base 1 .ctor called
Base 2 .ctor called
Even if you write base2 constructor as below, output will be the same as mentioned above.
public Base2() : base()
{
Console.WriteLine("Base 2 .ctor called");
}