6.3. Collections of Supertypes

We said earlier that arrays, as simple collections, contain items (either simple types or objects) that are all of the same type: all int(egers), for example, or all (references to) Student objects. However, the power of inheritance can be used to make arrays more versatile in the types of objects that they can hold.

If we declare an array to hold objects of a given type (for example, Person), we're free to insert objects explicitly declared to be of type Person or of any types derived from Person (for example, UndergraduateStudent, GraduateStudent, and Professor). This is because of the "is a" nature of inheritance; UndergraduateStudent, GraduateStudent, and Professor objects, as subclasses of Person, are simply special cases of Person objects. The C# compiler would therefore be perfectly happy to see the following code:

Person[] people = new Person[100];  // of Person object references

Professor p = new Professor();
UndergraduateStudent s1 = new UndergraduateStudent();
GraduateStudent s2 = new GraduateStudent();

// Add a mixture of professors and students in random order to the array.

people[0] = s1;
people[1] = p;
people[2] = s2;
// etc.

Objects of any type can be added to non–generic collections (excluding arrays), but this flexibility can lead to problems down the road. Generic collection classes automatically provide type-checking when elements are added, but this feature seemingly restricts them to store references of only a given type. Luckily, the power of inheritance can be used to make generic collections more versatile as well. For example, here is the preceding code snippet rewritten to use a generic List collection declared to hold Person references; then a variety of Professor, GraduateStudent, and UndergraduateStudent references are added to the List:

List<Person> people = new List<Person>();  // of Person object references

Professor p = new Professor();
UndergraduateStudent s1 = new UndergraduateStudent();
GraduateStudent s2 = new GraduateStudent();

// Add a mixture of professors and students in random order to the array.

people.add(s1);
people.add(p);
people.add(s2);
// etc.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset