Wednesday, October 22, 2008

Generic Collections

system.collections.Generic

Interfaces

IEnumerable<T> is the interface that allows to enumerate throught the collection.
ICollection<T> is the generic collection and adds the index capability.
IList<T> implements both IEnumerable<T> and ICollection<T>.

Concrete Implementations
List<T> implements both IList<T> and is basically uses an array behind the scene whose size is dynamically increased as required. Default Initial size being 4. Equivalent non-generic type is ArrayList.

List<T> has lot of capabilities ,but if we want to store a collection of key,value pairs there is another collection available - Dictionary<T> . Equivalent non-generic type is HashTable.

Other collections of interest are- SortedList<T> , LinkedList<T>, Queue<T> ,Stack<T> .

There is no SortedList<T> , but List<T> has sort() method to do the same. But if we want to keep the list sorted always we will need to write some code to do so..

Combining these collections with LINQ provides a lot of cool possibililities for every day scenarios . LINQ requires the object to implement IEnumerable or IQueryable interface.

The best part is that these new generic classes and interfaces are compatible with the old non-generic ones.
public class List :
IList, ICollection, IEnumerable, IList, ICollection, IEnumerable

This means if existing methods uses old interfaces as parmaeter, you still can supply the generic ones.

If you are planning to change all your existing non-generic types in your project to the generic one to improve performance and type safety make sure the generic ones has all the properties and methods available. In most case it may not be a one-to-one mapping.

No comments: