Wednesday 31 August 2016

IEnumerable VS ICollection

Enumerable

First of all, it is important to understand, that there are two different interfaces defined in the .NET base class library. There is a non-generic IEnumerable interface and there is a generic type-safe IEnumerable interface.

The IEnumerable interface is located in the System.Collections namespace and contains only a single method definition. The interface definition looks like this:


    public interface IEnumerable
    {
        IEnumerator GetEnumerator();
    }
    

It is important to know that the C# language foreach keyword works with all types that implement the IEnumerable interface.

IEnumerable

Let’s now take a look at the definition of the generic and type-safe version called IEnumerable which is located in the System.Collections.Generic namespace:


    public interface IEnumerable<out T> : IEnumerable
    {
        IEnumerator GetEnumerator();
    }
    

As you can see the IEnumerable interface inherits from the IEnumerable interface. Therefore a type which implements IEnumerable has also to implement the members of IEnumerable.

ICollection

As you can imagine, there are also two versions of ICollection which are System.Collections.ICollection and the generic version System.Collections.Generic.ICollection.

Let’s take a look at the definition of the ICollection interface type:


    public interface ICollection : IEnumerable
    {
        int Count { get; }  
        bool IsSynchronized { get; }
        Object SyncRoot { get; }
     
        void CopyTo(Array array, int index);
    }
    

ICollection inherits from IEnumerable. You therefore have all members from the IEnumerable interface implemented in all classes that implement the ICollection interface.

ICollection

When we look at the generic version of ICollection, you’ll recognize that it does not look exactly the same as the non-generic equivalent:


    public interface ICollection<T> : IEnumerable<T>, IEnumerable
    {
        int Count { get; }
        bool IsReadOnly { get; }
     
        void Add(T item);
        void Clear();
        bool Contains(T item);
        void CopyTo(T[] array, int arrayIndex);
        bool Remove(T item);
    }
    

Which type should you depend on?

No comments:

Post a Comment