How to explicitly call base class constructor from child class in C#?

CsharpServer Side ProgrammingProgramming

Make use of this keyword in c# to call one constructor from another constructor To call a constructor which is present in parent class make use of base keyword

Example

To call a constructor which is present in another class make use of base keyword

class DemoBase{
   public DemoBase(int firstNumber, int secondNumber, int thirdNumber){
      System.Console.WriteLine("Base class Constructor");
      System.Console.WriteLine($"{firstNumber} {secondNumber} {thirdNumber}");
   }
}
class Demo : DemoBase{
   public Demo(int firstNumber, int secondNumber, int thirdNumber) : base(firstNumber, secondNumber, thirdNumber){
      System.Console.WriteLine("Derived class Constructor");
      System.Console.WriteLine($"{firstNumber} {secondNumber} {thirdNumber}");
   }
}
class Program{
   static void Main(){
      Demo obj = new Demo(1, 2, 3);
      Console.ReadLine();
   }
}

Output

Base class Constructor
1 2 3
Derived class Constructor
1 2 3
raja
Published on 04-Aug-2020 07:07:40
Advertisements