Test Your Knowledge: Exercises

Exercise 14-1. Create an abstract Animal class that has private members weight and name, and abstract methods Speak( ), Move( ), and ToString( ). Derive from Animal a Cat class and a Dog class that override the methods appropriately. Create an Animal array, populate it with Dogs and Cats, and then call each member’s overridden virtual methods.

Exercise 14-2. Replace the array in Exercise 14-1 with a List. Sort the animals by size. You can simplify by just calling ToString( ) before and after the sort. Remember that you’ll need to implement IComparable.

Exercise 14-3. Replace the list from Exercise 14-2 with both a Stack and a Queue. Remove the sort function. Output the contents of each collection and see the difference in the order in which the animals are returned.

Exercise 14-4. Rewrite Exercise 14-2 to allow Animals to be sorted either by weight or alphabetically by name.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.