Friday, May 30, 2008

A generic ListCollection<T> class

I blogged recently about using public Collection instead of public List. On The Visual Studio Code Analysis Team Blog they explained how to ensure that we could re-use List methods in our concrete instance of Collection generic class, if necessary. The catch there is that a developer has to remember to call base class constructor like

public class AddressCollection : Collection<Address> {
public AddressCollection() : base(new List<Address>()) { }
}

And I thought: why not to use generics to ensure that base class constructor is called? It works fine, I tested it:



using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq; 

namespace ProgrammerThoughts.Common {
  /// <summary>
  /// A generic Collection class which ensures that it actually contains generic List.
  /// This provides us with an ability to re-use any public method of List&lt;T&gt;
  /// with a simple shell function. Such a shell could be implemented in ListColection&lt;T&gt;.
  /// or in a concrete implermentation.
  /// </summary>
  public class ListCollection<T> : Collection<T>
    where T : class {
    public ListCollection()
      : base(new List<T>()) {
    } 

    /// <summary>
    /// You can implement such shell methods in your concrete implementations of this generic instead.
    /// </summary>
    /// <param name="match">An actual function of type Predicate&lt;T&gt;</param>
    /// <returns></returns>
    public T Find(Predicate<T> match) {
      List<T> items = (List<T>)Items;
      return items.Find(match);
    }
  }
}