Creating Collection Class with Indexer

foreach has nothing to do with indexers. You need to declare a GetEnumerator method that returns an enumerator for the collection. (While you’re at it, it may be wise to implement the IEnumerable interface as well, which provides this method.) In your particular case, you can do it easily like this:

class Garage : IEnumerable
    private List cars = new List();

    public Car this[int i]
        get { return cars[i]; }

    // For IEnumerable
    public IEnumerator GetEnumerator() { return cars.GetEnumerator(); }

    // For IEnumerable
    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }

A huge benefit of implementing the IEnumerable interface is that you can use all the LINQ extension methods, e.g. Where and Select, for example:

var redCars = myGarage.Where(car => car.Color == CarColor.Red);


One thought on “Creating Collection Class with Indexer

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s