C# - default parameter values from previous parameter
- by Sagar R. Kothari
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;
}