Praveen
Praveen

Reputation: 186

array of same objects

If i want to declare an array of same objects(I mean same constructor paramter values). can i do it in one shot.

In the below example If i want to create 4 box objects with same dimensions (3, 3, 2), I called the constructor 4 times. Can i do this in one shot?

class Program
{
    static void Main(string[] args)
    {
        Box b = new Box(3, 4, 7);
        Console.WriteLine(b.getVolume());

        Box[] matchBoxes = new Box[4];
        matchBoxes[0] = new Box(3, 3, 2);
        matchBoxes[1] = new Box(3, 3, 2);
        matchBoxes[2] = new Box(3, 3, 2);
        matchBoxes[3] = new Box(3, 3, 2);


        Console.ReadLine();

    }


}

class Box
{
    private int length;
    private int breadth;
    private int height;
    public Box(int l, int b, int h)
    {
        this.length = l;
        this.breadth = b;
        this.height = h;
    }
    public int getVolume()
    {
        return (this.length*this.breadth*this.height);
    }

}

Upvotes: 2

Views: 636

Answers (7)

Damith
Damith

Reputation: 63065

var matchBoxes = Enumerable.Repeat(new Box(3, 3, 2), 4).ToArray();

Upvotes: 1

sehe
sehe

Reputation: 393064

Many of the answers are spot on (use a struct, use a loop);

Just to be complete:

    Box[] matchBoxes = Enumerable.Repeat(new Box(3, 3, 2), 4).ToArray();

Note as Marc Gravell stated that this will NOT give separate copies of the Box, unless it is a valuetype.

You could even make it more general:

    var generator   = Enumerable.Repeat(new Box(3, 3, 2));

    // ....
    var fourBoxes   = generator.Take(4);
    var twentyBoxes = generator.Take(20);

Upvotes: 1

Jarek
Jarek

Reputation: 166

I hope this solve your problem,

Box[] matchBoxes = new Box[]{ new Box(3, 3, 2), new Box(3, 3, 2), new Box(3, 3, 2), new Box(3, 3, 2)};

Upvotes: 0

Saeed Neamati
Saeed Neamati

Reputation: 35822

Why not using a loop, with parameters to be passed in constructors?

Upvotes: 0

Karel Frajták
Karel Frajták

Reputation: 4489

If you want to create 4 new objects, you have to call constructor 4 times. If you do not want to type it, use cycle:

for(int i = 0; i < 4; i++) matchBoxes[i] = new Box(3, 3, 2); 

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062855

That depends. Since this is a class you would need to call new 4 times if you want to get 4 different objects. However, your box looks to be immutable; if you are happy to use the same object 4 times (which might be reasonable here), you could use:

var box = new Box(3,3,2);
var matchBoxes = new[] {box,box,box,box};

If that is the entirety of your Box type, you might also want to consider making it a struct (immutable, small, value-esque - definitestruct candidate). Then it is moot : it will be a different value in each position. The construction could be the same as above, though.

Upvotes: 3

Guy
Guy

Reputation: 5528

Nope. each object needs to be created separately. Use a loop :)

Upvotes: 0

Related Questions