C# Call Constructor from Constructor


Inside a c# class , you can call a constructor from  constructor using the keyword this.

 //The constructor calls the constructor which takes 0 parameters as input

    public Box(int length, int width)    : this()

    {

        this.Length = length;

        this.Width = width;

    }

 

 

    //The constructor call the constructor which takes 2 parameters as input

    public Box(int length, int width, int height)   : this(length, width)

    {

 

        this.Heigth = height;

    }



The below Example program demonstrates calling a constructor from Constructor in C#

Call Constructor from Constructor C# Example Program



using System;

 

//C# class for Box

class Box

{

    //Private fields

    private int Length;

    private int Width;

    private int Heigth;

 

 

    public Box()

    {

        //Logic in Default Cosntructor

    }

 

 

    //The constructor calls the constructor which takes 0 parameters as input

    public Box(int length, int width)

        : this()

    {

        this.Length = length;

        this.Width = width;

    }

 

 

    //The constructor call the constructor which takes 2 parameters as input

    public Box(int length, int width, int height)

        : this(length, width)

    {

 

        this.Heigth = height;

    }

 

 

 

    //Public Method to calculate volume

    public int Volume()

    {

        return this.Length * this.Width * this.Heigth;

    }

 

}

 

 

//Using Class in the program

class ProgramCall

{

 

    public static void Main()

    {

        Box mybox = new Box(10, 20, 30);

 

        int Area = mybox.Volume();

 

        Console.WriteLine(Area);

 

        Console.Read();

    }

}

 

//Output

//6000




Call Constructor from Constructor C#, C# this constructor, c#.net Constructor this, Call constructor from another constructor using c# program