Reputation: 24810
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;
}
Upvotes: 0
Views: 88
Reputation: 42444
Constructor overloading is the nicest/cleanest solution. If you only want to have just one constructor you could use a params array. This only works if the parameters are of the same type.
public clas BOX
{
public BOX (params double[] d)
{
switch(d.Length)
{
case 3:
height = d[0];
length = d[1];
breadth = d[2];
break;
case 2:
height = d[0];
breadth = d[1];
length = d[0];
break;
case 1:
height = d[0];
breadth = d[0];
length = d[0];
break;
case 0:
// no parameters
break;
default:
// we rather not throw
// http://msdn.microsoft.com/en-us/library/ms229060(v=vs.110).aspx
// throw new ArgumentException();
Debug.Assert(d.Length<4, "too many arguments");
break;
}
}
}
Upvotes: 1
Reputation: 5846
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);
Upvotes: 4