Search code examples
c#constructoroverloadingdefault-parameters

C# - default parameter values from previous parameter


namespace HelloConsole
{
    public class BOX
    {
        double height, length, breadth;

        public BOX()
        {

        }
        // here, I wish to pass 'h' to remaining parameters if not passed
        // FOLLOWING Gives compilation error.
        public BOX (double h, double l = h, double b = h)
        {
            Console.WriteLine ("Constructor with default parameters");
            height = h;
            length = l;
            breadth = b;
        }
    }
}

// 
// BOX a = new BOX(); // default constructor. all okay here.
// BOX b = new BOX(10,20,30); // all parameter passed. all okay here.

// BOX c = new BOX(10);
// Here, I want = length=10, breadth=10,height=10;

// BOX d = new BOX(10,20);
// Here, I want = length=10, breadth=20,height=10;

Question is : 'To achieve above, Is 'constructor overloading' (as follows) is the only option?

public BOX(double h)
{
    height = length = breadth = h;
}

public BOX(double h, double l)
{
    height = breadth = h;
    length = l;
}

Solution

  • You can create multiple constructors calling each other:

    public BOX(double h) : this(h, h, h) { }
    public BOX(double h, double l) : this(h, l, h) { }
    public BOX(double h, double l, double b)
    {
        height = h;
        length = l;
        breadth = b;
    }
    

    Another solution is to use default values of null:

    public BOX(double h, double? l = null, double? b = null)
    {
        height = h;
        breadth = b ?? h;
        length = l ?? h;
    }
    

    This last approach also lets you call it with height and breadth only:

    var box = new BOX(10, b: 15); // same as new BOX(10, 10, 15);