Dog[] dogs = new Dog[7];
dogs[5] = new Dog();
dogs[0] = new Dog();

According to the book I'M reading the second two lines here create instances but the first only creates an array.
I'M still learning how to program but it looks to me like the fist line is also creating an instance. And it also seem
like that would be better anyway. If you have to explicitly tell each element in the array that it's an object, then that's just as much
typing as if you never used an array in the first place. Again remember, I'M learning.

Think of it as the first line creating a reference to a logical grouping of common elements. The subsequent lines are actually creating instances of the type of the element. The reason arrays are beneficial goes back to the first statement, the common elements are grouped together, which allows you to easily iterate over them. Tell me what code is easier to type, read, and modify?

Dog dog1 = new Dog();
Dog dog2 = new Dog();
Dog dog3 = new Dog();
Dog dog4 = new Dog();
Dog dog5 = new Dog();
Dog dog6 = new Dog();
Dog dog7 = new Dog();

DoSomethingWithDog(dog1);
DoSomethingWithDog(dog2);
DoSomethingWithDog(dog3);
DoSomethingWithDog(dog4);
DoSomethingWithDog(dog5);
DoSomethingWithDog(dog6);
DoSomethingWithDog(dog7);

// later on

DoSomethingElseWithDog(dog1);
DoSomethingElseWithDog(dog2);
DoSomethingElseWithDog(dog3);
DoSomethingElseWithDog(dog4);
DoSomethingElseWithDog(dog5);
DoSomethingElseWithDog(dog6);
DoSomethingElseWithDog(dog7);

Or

Dog[] dogs = new Dog[7];

for (int i = 0; i < dogs.Length; i++)
{
      dogs[i] = new Dog();
      DoSomethingWithDog(dogs[i]);
}

// later on

foreach (Dog dog in dogs)
{
      DoSomethingElseWithDog(dog);
}
Comments
Fine explanation!
This article has been dead for over six months. Start a new discussion instead.