Sunday 18 December 2011

Inheriting from a Generic Collection

You're probably familiar with generics in C#. For example, if you wanted to create a strongly-typed list of Car objects, where Car is defined as:

internal class Car
{
     public string Manufacturer { get; set; }
     public string Model { get; set; }
}
Then you can create a list with the statement:

var cars = new List<Car>();
However, you can also create a custom Car collection class or Abstract Data Type (ADT) with very little effort. By little effort, I mean that you do not need to concern yourself with managing the state of the collection class and implementing your own Add(...), Remove(...) etc. methods. To accomplish this, you can simply inherit from a generic List of the type you want a collection class for. So if we wanted our own "Cars" collection class, we can define the class as:

internal class Cars : List<Car>
{
     //... we inherit all of the List class' functionality
}
Pretty simple. Now we have a strongly-typed collection class to store our Car objects in. Furthermore, we do not need to write unit tests as we didn't write any custom logic to manage the internal state of our new collection class. To use our new class, it's as simple as newing up an object of the Cars class, and making use of all those useful List methods you're already familiar with...!

var cars = new Cars();
cars.Add(new Car() { Manufacturer="Porsche", Model="Cayman" });
cars.Add(new Car() { Manufacturer="Mercedes", Model="C Class" });

cars.ForEach(
    c => Console.WriteLine("{0} - {1}", c.Manufacturer, c.Model));

No comments:

Post a Comment