You can instantiate each item of the array in one statement:
Person[] myPeople =
{
new Person("John", "Doe"),
new Person("Jane", "Doe")
};
I usually use this syntax whenever I know in advance the values of an
array that I'm creating.
One thing to note: Your line:
Person[] myPeople = new Person[5];
creates the array, but does not instantiate the objects in the array.
So when you call:
myPeople[0].firstName = "George";
it will throw a NullReferenceException because myPeople[0] has not
been instantiated yet.
On Feb 11, 12:59 pm, Tom <[email protected]> wrote:
> Let's say I have an class called Person which takes two parameters:
> firstName and lastName.
>
> I can instantiate the object like so (c#)
>
> Person myPerson = new Person ("George","Washington");
>
> Now let's say I want to populate an array of objects based on the
> Person class. How do I do this?
>
> Person[] myPeople = new Person[5]; // I have declared an array of
> objects.
> myPeople[0].firstName = "George";
> myPeople[0].lastName = "Washington";
>
> OK, I populated the first occurance of the array of objects, but how
> can I do it on one line like I did when it was not an array?
>
> Thanks in advance for your help.