Magical Collection of .NET

Posted on May 17, 2007 @ 17:58 csharp

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
2
3
4
5
6
7
8
9
10
11
  [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 implements IEnumerable, so if you're just iterating through a collection, consider passing it as IEnumerable instead of a specific type of collection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  [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…

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

This can be re-written too…

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