Jack Smother
Jack Smother

Reputation: 207

declaring an array of objects with different parameters

C# programming class typeObject[] array = new typeObject[5]; Furthermore, the typeObject has a constructor that takes in an integer. How do you call each object with different integers than relying on default constructor? Thank you.

Upvotes: 0

Views: 2015

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149108

There's nothing wrong with using the code you cited in your comment:

typeObject[] array = new typeObject[5];
array[0] = new typeObject(7); // note: array indexes start at 0
array[1] = new typeObject(3);
array[2] = new typeObject(15);
...

But if you'd like to do it one statement, you can always use the array initializer syntax:

typeObject[] array = new typeObject[] 
{
    new typeObject(7),
    new typeObject(3),
    new typeObject(15),
};

Upvotes: 1

William
William

Reputation: 1875

You may either construct the elements in the array directly:

typeObject[] array = new typeObject[5];
array[0] = new typeObject(1);
array[1] = new typeObject(2);

or you may use array initializers:

typeObject[] array = new typeObject[]{new typeObject(1), new typeObject(2), ... new typeObject(5)};

Upvotes: 3

Related Questions