Collections in C#

Here we will study Collections in C# and their use. First its important to note here that Collections play an important role in LINQ.

So let's start with the topic of Collections.

First of all let us try to understand why Collections were introduced in the .NET framework.

Let us consider an array of string data as in the following:

  1. static void Main(string[] args)  
  2. {  
  3.    //Make an array of string data.  
  4.    string[] strArray= {"first","Second","Third"};  
  5.   
  6.    //Show no. of items in array using length property.  
  7.    Console.Writeline("This array has {0} items.",strArray.Length);  
  8.    Console.Writeline();  
  9.   
  10.    //Display contents using enumerator.  
  11.    foreach(string s in strArray)  
  12.    {  
  13.       Console.Writeline("Array Entry: {0}",s);  
  14.    }  
  15.    Console.Writeline(); 
    }

Now as you see I have made an array of three items. Now suppose I want to add a new item at the end of the array at the index[3].

So what will happen here is it will give a run time exception because arrays are fixed size containers. So here we require a more flexible data container that can dynamically resize our structure as we insert or remove items. Here Collections are useful.

The following four points will make Collections more clear.

  1. Collections resize the structure so that the previous data is not lost.
  2. They don't take contiguous memory.
  3. Dynamic Collection
  4. Every class whose parent is IEnumerable and implements the IEnumerator interface comes under the category of Collection classes.

Now the Collection classes are divided into the following two major categories:

  1. Non-generic
  2. Generic

Non-Generic

These classes are in the namespace System.Collections. They may contain N number of elements and a heterogeneous collection of elements because the type of any non-generic collection is fixed, in other words System.Object. So whatever data type we use will be implicitly type cast it into System.Object.

Generic

Generic Collections are in the namespace System.Collections.Generic. They also behave as a Collection but unlike non-generic Collections they do not have a pre-defined data type. So we need to define at run time an object declaration of a Generic Collection class with angular braces. So it may contain a collection of homogeneous elements and will return the same data type that is assigned to the object Collection.

Now let us talk about the IEnumerable class and IEnumerator interface. Note the class whose parent is an IEnumerable class and implements the IEnumerator interface will act as a Collection class and the object of that class can use a Foreach loop.

Now for the the golden rule for the Collection class. Whenever a collection class is in a Foreach loop the .Net Framework will check the following two things:

  1. Whether the class is implementing an IEnumerator interface.
  2. Secondly it will ask for the number of items in the IEnumerable class.
  1. Class program  
  2. {  
  3.    static void Main(string[] args)  
  4.    {  
  5.       var school= new school();  
  6.       foreach(var student in school)  
  7.    {  
  8. }  

In the preceding code, as soon as the .Net framework finds the school class in the foreach loop, it will check if the school class is deriving from an IEnumerable class and secondly it will ask for the IEnumerator interface of the school class that will declare the contents of the school class.

Class school :IEnumerable
internal class StudentEnumerator: IEnumerator


Note that the IEnumerable class acts as the Counter class and it should have the individual existence.

In the preceding two lines of code I have simply declared an IEnumerable class and an StudentEnumerator interface.

Now I will return an instance of the StudentEnumerator interface in the GetEnumerator method.

  1. public IEnumerator GetEnumerator()  
  2. {  
  3.    return new StudentEnumerator();  

Also note that one instance of the Enumerator class should be a forward-only cursor and it cannot reset itself. Moreover it cannot tell the length of the data.

As soon as we return an instance of the Enumerator class it will be asked using a method named "Move Next" do you have the data and after the .Net Framework gets the call from the IEnumerator by the property called "Current". the IEnumerator will take the current data and pass it to the .Net Framework by returning the address of the data.

So basically the chain goes like:

Move Next -> Yes > Current-> Address.

Note that the Enumerator is a read-only interface. It just returns the address of the data.

To avoid the threads we can add the namespace System.Collections.Synchronization.

Now note in the preceding code the StudentEnumerator class does not have an object of the school class.

We will use here constructors to do this.

  1. public StudentEnumerator(Student ram,Student suresh,Student ashok)  
  2. {  
  3.    _ram=ram;  
  4.    _suresh=suresh;  
  5.    _ashok=ashok;  
  6. }  
  7.   
  8. private Student current= null;  
  9. private bool_iterationcomplete= true;  
  10. public object current  
  11. {  
  12.    get  
  13.    {  
  14.       return_ current;  
  15.    }  
  16. }  
  17. public bool MoveNext()  
  18. {  
  19.    if(_iterationComplete==true)  
  20.    if(_current== null)  
  21.    return false;  
  22.    {  
  23.       _current=_ram;  
  24.       return true;  
  25.    }  
  26.    else if(_current==_ram)  
  27.    {  
  28.       _current=_suresh;  
  29.       return true;  
  30.    }  
  31.    else if(_current==_suresh)  
  32.    {  
  33.       _current=_ashok;  
  34.       return true;  
  35.    }  
  36.    else if (_current==_ashok)  
  37.    {  
  38.       _current=null;  
  39.       return false;  
  40.    }  

Now update the main method as follows:

  1. static void Main(string[] args)  
  2. {  
  3.    var school= new school();  
  4.    for each(var student in school)  
  5.    {  
  6.       var enumerator=school.GetEnumerator();  
  7.       while(Enumerator.MoveNext)  
  8.       {  
  9.          Student student=(Student)Enumerator.Current;  
  10.          Console.Writeline(Student.Name);  
  11.       }  
  12.    }  
  13. }

I have tried my best to describe Collections in C#. Still if anyone has queries regarding the article then do provide your valuable comments.

Up Next
    Ebook Download
    View all
    Learn
    View all