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.
2 Answers
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)};
2 Comments
Jack Smother
for the first option, wouldn't the first statement declare all the objects with the default constructor though? Thank you @William
p.s.w.g
@LeonardLie In the first code example, each element of the array would be initialized to the default value of
typeObject. If that's a class, then each element would be null. If that's a struct, e.g. a DateTime, then it would be roughly equivalent to calling the parameterless constructor for the struct--although you can't actually define a custom parameterless constructor for a struct, the compiler provides it for you.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),
};
3 Comments
Jack Smother
Thank you. So, the first statement in your second code would not call the default constructor of the typeObject class? @p.s.w.g
p.s.w.g
@LeonardLie The second code block only contains a single statement, which constructs N objects using the specified constructor (not a parameterless one) and initializes a new array which contains those objects as elements.
David Arno
No, it just creates the array. The elements of the array are empty until initialise with the new typeObject() statements.