Understanding Generics—Creating a Custom Generic Collection
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Creating a Custom Generic Collection
As you have seen, the System.Collections.Generic namespace provides numerous types that allow
you to create type-safe and efficient containers. Given the set of available choices, the chances are
quite good that you will not need to build custom collection types when programming with .NET
2.0. Nevertheless, to illustrate how you could build a stylized generic container, the next task is to
build a generic collection class named CarCollection<T>.
Like the nongeneric CarCollection created earlier in this chapter, this iteration will leverage an
existing collection type to hold the subitems (a List<> in this case). As well, you will support foreach
iteration by implementing the generic IEnumerable<> interface. Do note that IEnumerable<> extends
the nongeneric IEnumerable interface; therefore, the compiler expects you to implement two versions
of the GetEnumerator() method. Here is the update:
public class CarCollection<T> : IEnumerable<T> { private List<T> arCars = new List<T>(); public T GetCar(int pos) { return arCars[pos]; } public void AddCar(T c) { arCars.Add(c); } public void ClearCars() { arCars.Clear(); } public int Count { get { return arCars.Count; } } // IEnumerable<T> extends IEnumerable, therefore // we need to implement both versions of GetEnumerator(). IEnumerator<T> IEnumerable<T>.GetEnumerator() { return arCars.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return arCars.GetEnumerator(); } }
You could make use of this updated CarCollection<T> as so:
static void Main(string[] args) { Console.WriteLine("***** Custom Generic Collection *****\n"); // Make a collection of Cars. CarCollection<Car> myCars = new CarCollection<Car>(); myCars.AddCar(new Car("Rusty", 20)); myCars.AddCar(new Car("Zippy", 90)); foreach (Car c in myCars) { Console.WriteLine("PetName: {0}, Speed: {1}", c.PetName, c.Speed); } Console.ReadLine(); }
Here you are creating a CarCollection<T> type that contains only Car types. Again, you could
achieve a similar end result if you make use of the List<T> type directly. The major benefit at this
point is the fact that you are free to add unique methods to the CarCollection that delegate the
request to the internal List<T>.
|

