Collection Types - Lists

One thing that is missing from ICollection<T>, and for good reason, is an index operator that allows you to access the items within the collection using the familiar array-access syntax. The fact is that not all concrete types that implement ICollection<T> need to have an index operator, and in some of those cases, it makes no sense for them to have an index operator. For example, an index operator for a list of
integers would probably accept a parameter of type int, whereas a dictionary type would accept a parameter type that is the same as the key type in the dictionary.

If you’re defining a collection where it makes sense to index the items, then you want that collection to implement IList<T>. Concrete generic list collection types typically implement the IList<T> and IList interfaces. IList<T> implements ICollection<T>, and IList implements ICollection, so any type that is a list is also a collection. The IList<T> interface looks like the following:

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
T this[ int index ] { get; set; }
int IndexOf( T item );
void Insert( int index, T item );
void RemoveAt( int index );

The IList interface is a bit larger:

public interface IList : ICollection, IEnumerable
bool IsFixedSize { get; }
bool IsReadOnly { get; }
object this[ int index ] { get; }
int Add( object value );
void Clear();
bool Contains( object value );
int IndexOf( object value );
void Insert( int index, object value );
void Remove( object value );
void RemoveAt( int index );

As you can see, there is some overlap between IList<T> and IList, but there are plenty of useful properties and methods in IList that a generic container such as List<T>, or any other generic list that you create, would want. As with ICollection<T> and ICollection, the typical pattern is to implement both interfaces. You should explicitly implement the methods of IList that overlap in functionality with those of IList<T>, so that the only way to get to them is to convert the instance reference to the IList type first.

Source Of Information : Apress Accelerated C Sharp 2010


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner