Wednesday, March 29, 2017

Comparison between List, IList and IEnumerable

  • IEnumerable<T> is the base interface that the following extend or implement. It doesn't allow for direct access and is readonly. So use this only if you intend to iterate over the collection.
  • ICollection<T> extendsIEnumerable<T> but in addition allows for adding, removing, testing whether an element is present in the collection and getting the total number of elements. It doesn't allow for directly accessing an element by index. That would be an O(n) operation as you need to start iterating over it until you find the corresponding element.
  • IList<T> extends ICollection<T> (and thus it inherits all its properties) but in addition allows for directly accessing elements by index. It's an O(1) operation.
  • List<T> is just a concrete implementation of the IList<T> interface.
IEnumerable is the base of the ICollection and IList interfaces

public interface IEnumerable
{
IEnumerator GetEnumerator();
}
public interface ICollection : IEnumerable
{
int count { get; }
bool IsSynchronized { get; }
Object SyncRoot { get; }
void CopyTo(Array array,int index);
}
public interface ICollection : IEnumerable, IEnumerable
{
int count { get; }
bool IsReadOnly { get; }
void Add(T item);
void Clear();
bool Contains(T item);
void CopyTo(T[] array, it arrayIndex);
bool Remove(T item);
}
public interface IList : ICollection,IEnumerable
{
bool IsFixedSize { get; }
bool IsReadOnly { get; }
Object this[int index] { get;set; }
int Add(Object value);
int IndexOf(Object value);
void Insert(intindex,object value);
void Remove(Object value);
void RemoveAt(int index);
}

When to Use?

Now since we know all interfaces, the next question we have is when we have to use which interface?
The important point is to use the interface that our application needs us to use.
InterfaceBest Practices
IEnumerableIEnumerable<T>The only thing you want is to iterate over the elements in a collection.
You only need read-only access to that collection.
ICollectionICollection<T>You want to modify the collection or you care about its size.
IListIList<T>You want to modify the collection and you care about the ordering and / or positioning of the elements in the collection.
ListList<T>As per DIP, you should depend on abstractions instead of implementations, you should never have a member of your own implementations with the concrete type List/List.

No comments:

Post a Comment