C# - default parameter values from previous parameter

Posted by Sagar R. Kothari on Stack Overflow See other posts from Stack Overflow or by Sagar R. Kothari
Published on 2014-08-23T10:10:31Z Indexed on 2014/08/23 10:20 UTC
Read the original article Hit count: 232

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;
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about constructor