More Things to Do with Generic Objects
Now that we have a generic collection class, what else can we do with it? Listing 6 demonstrates some additional ways to manipulate our generic collection class.
Listing 6 More collection manipulation.
Contractor contractor = new Contractor("A Contractor"); Employee employee = new Employee("An Employee"); GenericCollection<Person> genericCollection = new GenericCollection<Person>(); Console.WriteLine("Collection capacity: " + genericCollection.MyGenericCollection.Capacity); genericCollection.MyGenericCollection.Add(employee); genericCollection.MyGenericCollection.Add(contractor); foreach (Person p in genericCollection) { Console.WriteLine("Person called: " + p.Name); } Console.WriteLine("Number of entries: " + genericCollection.MyGenericCollection.Count); genericCollection.MyGenericCollection.Remove(employee); Console.WriteLine("Number of entries: " + genericCollection.MyGenericCollection.Count); Console.ReadLine();
Listing 7 shows what this code output in Listing 6 produces.
Listing 7 Collection manipulation.
Collection capacity: 0 Person called: An Employee Person called: A Contractor Number of entries: 2 Number of entries: 1
Notice that the initial capacity of the collection is zero. In other words, the collection grows dynamically as elements are added. When I've added two objects to the collection, I can retrieve this number by using the Count property. I can also remove elements from the collection by using the Remove() method. I simply pass in the object that I want to remove, and it's taken out of the collection.
What happens if I try to remove an element that hasn't been added to the collection? Consider the employee1 object in Listing 8.
Listing 8 Removing an element that wasn't added to the collection.
Contractor contractor = new Contractor("A Contractor"); Employee employee = new Employee("An Employee"); Employee employee1 = new Employee("An Employee"); GenericCollection<Person> genericCollection = new GenericCollection<Person>(); Console.WriteLine("Collection capacity: " + genericCollection.MyGenericCollection.Capacity); genericCollection.MyGenericCollection.Add(employee); genericCollection.MyGenericCollection.Add(contractor); foreach (Person p in genericCollection) { Console.WriteLine("Person called: " + p.Name); } Console.WriteLine("Number of entries: " + genericCollection.MyGenericCollection.Count); genericCollection.MyGenericCollection.Remove(employee1); Console.WriteLine("Number of entries: " + genericCollection.MyGenericCollection.Count); Console.ReadLine();
For the output from this code, see Listing 9.
Listing 9 The element removal fails silently.
Collection capacity: 0 Person called: An Employee Person called: A Contractor Number of entries: 2 Number of entries: 2
Notice that no element is removed from the collection—I never added the employee1 object, so it can't be removed.
What happens if we want to sort the elements of a generic collection? Let's look at that possibility next.