0

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.

1
  • I meant to declare each index of the array to a different passed parameter for the constructor. Essentially what I want is array[1] = new typeObject(3); array[2] = new typeObject(15); ... Commented Oct 11, 2013 at 5:15

2 Answers 2

3

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)};
Sign up to request clarification or add additional context in comments.

2 Comments

for the first option, wouldn't the first statement declare all the objects with the default constructor though? Thank you @William
@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.
1

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

Thank you. So, the first statement in your second code would not call the default constructor of the typeObject class? @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.
No, it just creates the array. The elements of the array are empty until initialise with the new typeObject() statements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.