Collection in C# - Part Two

In our previous article we discussed about IEnumerator, IEnumerable and their generic counterparts. They are basic building blocks of every collection type in C#. Every collection is implemented from them and from other also. IEnumerable is used when you want to just traverse data without  modification. In ICollection you can traverse data as well as count the number of elements. In this article we will discuss about ICollection, IList and their generic parts.

Previous Article

ICollection

ICollection belongs to System.Collections namespace.

IEnumerable provides only traversing. We can’t access random element using index and can’t count number of elements. If we try to access IEnumerable element through indexing we will get error “Cannot apply indexing with [] to an expression of type 'IEnumerable' ." Same with ICollection but ICollection is littlemore advanced than IEnumerable. In ICollection we can count element. ICollection implement IEnumerable Interface.

Implementation of ICollection

  1. namespace System.Collections  
  2. {  
  3.     public interface ICollection : IEnumerable  
  4.     {          
  5.         int Count { get; }  
  6.         bool IsSynchronized { get; }  
  7.         object SyncRoot { get; }  
  8.         void CopyTo(Array array, int index);  
  9.     }  
  10. }  

ICollection implements all members of IEnumerable and above function. It is also a very good example of inheritance. We will discuss Inheritance in another article. As ICollection implements IEnumerable so we can traverse elements of ICollection using foreach loop but we can’t access through index or and can’t access a random variable. We can’t add and remove element in collection.

Description of Methods and Properties

  • Count- will return number of elements in collection.
  • CopyTo- Will Be used to copy collection to an array.
  • IsSynchronized- Indicates whether access to ICollection is synchronized or not to make it thread safe.
  • IsSynchronized - SyncRoot were dropped from generic version because thread safety is no longer belongs to the collection.

Example

  1. static void Main(string[] args)  
  2.         {  
  3.             int[] array = new int[] { 1, 2, 3, 4, 5 };           
  4.             ICollection collection = array;  
  5.             int[] copyArray= new int[5];  
  6.             Console.WriteLine("Total number of Element in collection {0}", collection.Count);  
  7.             //Traversing Collection  
  8.             foreach (var item in collection)  
  9.             {  
  10.                 Console.WriteLine("Item from collection {0}", item);  
  11.             }  
  12.             //Copying collection item to array  
  13.             collection.CopyTo(copyArray, 0);  
  14.             //Traversing copyArray  
  15.             foreach (var item in copyArray)  
  16.             {  
  17.                 Console.WriteLine("Item from Array {0}", item);  
  18.             }  
  19.         }  

output

ICollection<T>

ICollection<T> belongs to System.Collections.Generic namespace.

ICollection<T> is generic part of ICollection. Generic part has more functions than non-generic parts because generic is added later in c#. It has 4 extra methods Add, Remove, Clear and contains. We will not discuss already discussed method here. In ICollection<T> , more functionality is added but we can’t still access element through index. First we check the implementation then we will discuss every method.

Implementation of ICollection<T>

  1. namespace System.Collections.Generic  
  2. {  
  3.     public interface ICollection<T> : IEnumerable<T>, IEnumerable  
  4.     {          
  5.         int Count { get; }  
  6.         bool IsReadOnly { get; }  
  7.         void Add(T item);  
  8.         void Clear();  
  9.         bool Contains(T item);  
  10.         void CopyTo(T[] array, int arrayIndex);  
  11.         bool Remove(T item);  
  12.     }  
  13. }  

Description of Methods and Properties

  • Count – Count gives number of elements in collection.
  • IsReadOnly – States whether collection is read only or not if collection is read only than add, remove and clear through exception(NotSupportedExcaption).
  • Add- Add element to collection.
  • Clear- Removes all elements from collection.
  • Contains- Check whether an element exits in collection or not (return true or false).
  • CopyTo- Copy element to an array.
  • Remove- Removes an element from collection.

Example:

  1. static void Main(string[] args)  
  2.         {  
  3.             List<int> list = new List<int>();  
  4.             //use can also create in following way  
  5.             //ICollection<int> collection = new List<int>();  
  6.             ICollection<int> collection = list;  
  7.             //Adding element to collection       
  8.             collection.Add(10);  
  9.             collection.Add(20);  
  10.             collection.Add(30);  
  11.             collection.Add(40);  
  12.             //Traversing Collection   
  13.             foreach (var item in collection)  
  14.             {  
  15.                 Console.WriteLine("{0}", item);  
  16.             }  
  17.             //Removing Element  
  18.             collection.Remove(20);  
  19.             collection.Remove(30);  
  20.             //Traversing Collection after removing element  
  21.             Console.WriteLine("Collection after removing item");  
  22.             foreach (var item in collection)  
  23.             {  
  24.                 Console.WriteLine("{0}", item);  
  25.             }  
  26.             //Checking lement in collection  
  27.             if (collection.Contains(10))  
  28.             {  
  29.                 Console.WriteLine("Element Exits");  
  30.             }  
  31.             collection.Clear();  
  32.             Console.WriteLine("Collection after clearing items");  
  33.             foreach (var item in collection)  
  34.             {  
  35.                 Console.WriteLine(item);  
  36.             }  
  37.         }  

output

Note: You can use user defined datatype with generic part like class.

Example:

  1. public class Student  
  2.     {  
  3.         public int StudentID { getset; }  
  4.         public string StudentName { getset; }  
  5.     }  
  6. static void Main(string[] args)  
  7.         {  
  8.             ICollection<Student> student = new List<Student>();  
  9.             student.Add(new Student() { StudentID = 1, StudentName = "Devinder Yadav" });  
  10.             foreach (var item in student)  
  11.             {  
  12.                 Console.WriteLine("Your Id is {0} and Name is {1}", item.StudentID, item.StudentName);  
  13.             }  
  14.         }  

output

IList

IList belongs to using System.Collections namespace

IList have more functionally then ICollection. We can access random element, can remove and can access an element through index and more. We will discuss every method and property.

Implementation of IList

  1. namespace System.Collections  
  2. {  
  3.     public interface IList : ICollection, IEnumerable  
  4.     {  
  5.           
  6.         object this[int index] { getset; }  
  7.         bool IsFixedSize { get; }  
  8.         bool IsReadOnly { get; }  
  9.         int Add(object value);  
  10.         void Clear();  
  11.         bool Contains(object value);  
  12.         int IndexOf(object value);  
  13.         void Insert(int index, object value);  
  14.         void Remove(object value);  
  15.         void RemoveAt(int index);  
  16.     }  
  17. }  

Description of Methods and Properties

  • this- It will return element through indexing.
  • IsFixedSize –Tells collection is fixed size or not.
  • IsReadOnly- States whether collection is read only or not if collection is read only than add ,remove and clear through exception(NotSupportedExcaption).
  • Add- Add element to collection and return index of that element.
  • Clear- Removes all element from collection
  • Contains- Check an element in a collection exits or not.
  • IndexOf- Return index of an element.
  • Insert- Insert element at a index.
  • Remove- Remove an element
  • RemoveAt- Remove element from an index.

In below example I am not covering already discussed method.

Example:

  1. static void Main(string[] args)  
  2.         {  
  3.             IList list = new List<int>();  
  4.             list.Add(10);  
  5.             list.Add(20);  
  6.             list.Add(30);             
  7.             //add method in IList return index of added element.  
  8.             Console.WriteLine("Element 40 added at index {0}", list.Add(40));  
  9.             Console.WriteLine("Collection is of fixedtype {0}",list.IsFixedSize);  
  10.             Console.WriteLine("Index of element 20 is {0}", list.IndexOf(20));  
  11.             list.RemoveAt(3);  
  12.             foreach (var item in list)  
  13.             {  
  14.                 Console.WriteLine(item);  
  15.             }  
  16.         }  

Output:

output

IList<T>

IList<T> belongs to System.Collections.Generic namespace

Implementation of IList<T>

  1. namespace System.Collections.Generic  
  2. {  
  3.     public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable  
  4.     {  
  5.         T this[int index] { getset; }  
  6.         int IndexOf(T item);  
  7.         void RemoveAt(int index);  
  8.     }  
  9. }  

Description of Methods and Properties

  • This- It will return element through indexing.
  • IndexOf- Return index of an element.
  • RemoveAt-- remove element from an index.

All the above methods are discussed in IList section so I will not give an example.

If we can traverse a collection using foreach loop then it means, it implements IEnumerable interface.

Where to use

Use of IEnumerable, ICollection and there generic counterpart depends upon your requirement. These are basically for traversing element. When you have requirement of that type you can use them.

These collection types can be used to create your own type of collection. You can create your own collection by using them as a base class and add extra functionality according to your requirement. As these are interfaces you have to implement all the methods to use them.

Until now we have discussed all the interfaces of collection types. In the next article we will discuss about List, queue, stack and many others.

Read more articles on C#:

Up Next
    Ebook Download
    View all
    Learn
    View all