Home > Articles > Programming > Windows Programming

📄 Contents

  1. Introduction
  2. Inheriting from CollectionBase
  3. CollectionBase Implements IList, IListSource, and IEnumerable
  4. Implementing an Indexer
  5. Summary
  • Print
  • + Share This
From the author of

CollectionBase Implements IList, IListSource, and IEnumerable

The CollectionBase class implements the IList, IListSource, and IEnumerable interfaces. Collectively these interfaces support binding to controls like the DataGrid (for Windows forms and web forms) and enumerating the elements in the collection. Enumeration is most commonly expressed using a foreach statement. Listing 2 demonstrates how to iterate the elements in BeerInventory, assuming that there's a method Reorder and a property TimeToReorder defined in the collected type, Beer.

Listing 2—Iterate the Elements of the BeerInventory, Relying Implicitly on IEnumerable

BeerInventory inventory = BeerInventory.CreateTestInventory();
foreach(Beer beer in inventory)
 if( beer.TimeToReorder ) beer.Reorder();

Listing 2 creates a test inventory by using a test factory method. The factory method (not shown) creates an instance of BeerInventory and adds some test data to the instance. This is a habit I've developed over the years to make every class testable. The test method can be any static method that creates an instance of the object, initializes it, and allows exercising the capabilities of the class. (This is also referred to as scaffolding.)

The IEnumerable interface supports the foreach construct, and the example assumes a class, Beer, that implements TimeToReorder and Reorder. I would actually implement the foreach statement in Listing 2 as a method in my BeerInventory class, perhaps calling it BeerInventory.FillInventory. If you were using a System.Array of Beer objects, the FillInventory method would have to reside somewhere else, resulting in a semantics violation.

  • + Share This
  • 🔖 Save To Your Account