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!

 1 [TypeDependency("System.SZArrayHelper")]
 2   public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
 3   {
 4       // Methods
 5       int IndexOf(T item);
 6       void Insert(int index, T item);
 7       void RemoveAt(int index);
 8       // Properties
 9       T this[int index] { get; set; }
10   }

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

 1 [TypeDependency("System.SZArrayHelper")]
 2   public interface ICollection<T> : IEnumerable<T>, IEnumerable
 3   {
 4       // Methods
 5       void Add(T item);
 6       void Clear();
 7       bool Contains(T item);
 8       void CopyTo(T[] array, int arrayIndex);
 9       bool Remove(T item);
10   
11       // Properties
12       int Count { get; }
13       bool IsReadOnly { get; }
14   }

For instance the following code could be re-written…

1 public void Iterate( ICollection< T > records ) 
2   {
3     foreach( T record in records ) 
4     {
5          // do something that has no effect to records.
6      }
7   }

This can be re-written too…

1 public void Iterate( IEnumerable< T > records ) 
2   {
3     foreach( T record in records ) 
4     {
5          // do something that has no effect to records.
6      }
7   }
comments powered by Disqus