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
This gist of it is this... use the most abstract type! Instead of accepting a parameter of type List
IList
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 }
11
ICollection
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 }