0

I got next task: Add constructor that receives an arbitrary amount of objects of type Rectangle or an array of objects of type Rectangle.

To solve it, I made two constructors. But if I understood correctly by the conditions of the problem, it should be one constructor. How to combine them? Or is it impossible?

public ArrayRectangles(IEnumerable<Rectangle> rectangles)
    {
        rectangle_array = rectangles.ToArray();
    }

    public ArrayRectangles(Rectangle[] rectangle_array)
    {
        this.rectangle_array = new Rectangle[rectangle_array.Length];

        for (int i = 0; i < rectangle_array.Length; i++)
        {
            if (rectangle_array[i] != null)
            {
                this.rectangle_array[i] = new Rectangle(rectangle_array[i].GetSideA(), rectangle_array[i].GetSideB());
            }
        }
    }

1 Answers1

2

It seems that you are looking for params keyword:

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array.

public ArrayRectangles(params Rectangle[] rectangle_array)
{
    ...
}

Which allows to call method (ctor in this case) either with array of Rectangle or variable number of Rectangle parameters:

var foo = new ArrayRectangles(new Rectangle[0]);
var bar = new ArrayRectangles(new Rectangle(), new Rectangle());
Guru Stron
  • 102,774
  • 10
  • 95
  • 132