CHAPTER 9 COLLECTIONS AND GENERICS
public class CarCollection : IEnumerable
{
private ArrayList arCars = new ArrayList();
// Cast for caller.
public Car GetCar(int pos)
{ return (Car) arCars[pos]; }
// Insert only Car objects.
public void AddCar(Car c)
{ arCars.Add(c); }
public void ClearCars()
{ arCars.Clear(); }
public int Count
{ get { return arCars.Count; } }
}
// Foreach enumeration support.
IEnumerator IEnumerable.GetEnumerator()
{ return arCars.GetEnumerator(); }
However, a custom collection class does nothing to solve the issue of boxing/unboxing penalties.
Even if you were to create a custom collection named IntCollection that you designed to operate only
on System.Int32 items, you would have to allocate some type of object to hold the data (e.g.,
System.Array and ArrayList):
public class IntCollection : IEnumerable
{
private ArrayList arInts = new ArrayList();
// Get an int (performs unboxing!).
public int GetInt(int pos)
{ return (int)arInts[pos]; }
// Insert an int (performs boxing)!
public void AddInt(int i)
{ arInts.Add(i); }
public void ClearInts()
{ arInts.Clear(); }
public int Count
{ get { return arInts.Count; } }
}
IEnumerator IEnumerable.GetEnumerator()
{ return arInts.GetEnumerator(); }
Regardless of which type you might choose to hold the integers, you cannot escape the boxing
dilemma using nongeneric containers.
332