IEnumerable and ICollection

Hi Friends,

Now, in this section, we are going to talk about two most popular collections and their usages. IEnumerable lets you enumerate the collection. here, it only exposes one member known as GetEnumerator() method. Now, GetEnumerator() returns the enumerator. One important to understand here, that collections don’t iterate itself. It is basically done by enumerator and the sole purpose of IEnumerable is to supply enumerator to the collection. However, foreach works for all the collection. so, if i go ahead and implement the below logic, then also it will produce me the same result.


Now, ICollection declares an object for an in memory collection. However, the basic difference between ICollection and IEnumerable is ICollection is a write opeartion and IEnumerable is a readonly operation only meant for iteration. However, ICollection uses following to modify the collection.

  • Add()
  • Remove()
  • Clear()
  • IsReadOnly

Apart from this it also gives count of the collection and checks for containing element with contains(). Now, let me go ahead and discuss these properties one by one. In the below snippet, i have used the count property of the collection. Apart from that you can use other properties as well as shown below in the screen shot.



However, for Lists we can directly get the count by using count property on the variable and by using length on the array variable. But, the intention was to show the Collection properties here. Now, lets look at this implementation. This is explicit casting.

and if i see the output of this then it will produce the following result.


and the reason for this is that Arrays are readonly collection.

One more interface we is IReadonlyCollection. Now, this property is enumerable and also tells that how many elements it has. Another important interface is IList. Here, in this case elements can be accessed based on its index like string march = monthsofyear[2]; IList is also implemented by Arrays and Lists.

We’ll discuss all these interfaces and its imlementation in the coming sections. Till then stay tuned and happy coding.

Happy Coding

This entry was posted in C# and tagged . Bookmark the permalink.