17 May 2007

Magical Collections of .NET

by mo


For I came across a couple of pages that discuss the use of collections in C#. I found them to be very helpful and I thought I would share…

Collections vs. Generic Collections

How to use Collections

This gist of it is this… use the most abstract type! Instead of accepting a parameter of type List, which is a specific type of collection, consider using ICollection or IList!

IList implements ICollection so ICollection is a more generic type of IList. This allows for greater flexibility if you need to make changes under the hood!

  [TypeDependency("System.SZArrayHelper")]
  public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
  {
      // Methods
      int IndexOf(T item);
      void Insert(int index, T item);
      void RemoveAt(int index);
      // Properties
      T this[int index] { get; set; }
  }

ICollection<T> implements IEnumerable<T>, so if you’re just iterating through a collection, consider passing it as IEnumerable<T> instead of a specific type of collection.

  [TypeDependency("System.SZArrayHelper")]
  public interface ICollection<T> : IEnumerable<T>, IEnumerable
  {
      // Methods
      void Add(T item);
      void Clear();
      bool Contains(T item);
      void CopyTo(T[] array, int arrayIndex);
      bool Remove(T item);
  
      // Properties
      int Count { get; }
      bool IsReadOnly { get; }
  }

For instance the following code could be re-written…

public void Iterate(ICollection<T> records) 
{
  foreach(T record in records) 
  {
    // do something
  }
}

This can be re-written too…

public void Iterate(IEnumerable<T> records) 
{
  foreach(T record in records) 
  {
    // do something that has no effect to records.
  }
}
csharp