How can we call one constructor from another in the same 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

class Demo{
   public Demo(){
      System.Console.WriteLine("Parameter less constructor called");
   }
   public Demo(int firstNumber, int secondNumber) : this(){
      System.Console.WriteLine($"{firstNumber} {secondNumber}");
   }
   public Demo(int firstNumber, int secondNumber, int thirdNumber) : this(firstNumber, secondNumber){
      System.Console.WriteLine($"{firstNumber} {secondNumber} {thirdNumber}");
   }
}
class Program{
   static void Main(){
      Demo obj = new Demo(1, 2, 3);
      Console.ReadLine();
   }
}

Output

Parameter less constructor called
1 2
1 2 3

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

Example

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:00:14
Advertisements