IEnumerable Interface in C#

Background
 
Many times there is need to loop through collection of classes or List which are anonymous types, IEnumerable interface is one of the best feature of C# language which loop over the collection, let us learn about it step by step so beginners also can understand.
 
What is  IEnumerable interface ?
 
IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface, this allows readonly access to a collection then collection that implements IEnumerable can be used with a for-each statement.
 
Key Points
  1. IEnumerable interface contains in the System.Collections.Generic namespace.
  2. IEnumerable interface is generic interface which allows to looping over generic or non-generic list.
  3. IEnumerable interface also works with linq query expression.
  4. IEnumerable interface Returns an enumerator that iterates through the collection.

Let us implement the IEnumerable interface in a class as

  1. public class Customer : IEnumerable  
  2. {  
  3.   
  4.     public IEnumerator GetEnumerator()  
  5.     {  
  6.         throw new NotImplementedException();  
  7.     }  

In the above example you have seen that after implementing the IEnumerable Interface there is method called GetEnumerator along with interface IEnumerator which helps to get current element from the collection.

Methods of IEnumerator Interface
 
 IEnumerator is an interface which helps to get current element from the collection,its has following two methods
  1. MoveNext()
  2. Reset()

MoveNext()

Sets the enumerator to the next element of the collection, it Returns true if the enumerator was successfully sets to the next element and false if the enumerator has ed the end of the collection. 
 
Reset()

Sets the enumerator to its initial position, which is before the first element in the collection. 
 
Properties of IEnumerator Interface
 
IEnumerator Interface has property named  Current which returns the current element in the collection.
 
Let us implement the IEnumerator Interface in class as
  1. public class Customer : IEnumerator  
  2. {  
  3.   
  4.      public object Current  
  5.      {  
  6.         get { throw new NotImplementedException(); }  
  7.      }  
  8.   
  9.      public bool MoveNext()  
  10.      {  
  11.         throw new NotImplementedException();  
  12.      }  
  13.   
  14.      public void Reset()  
  15.      {  
  16.         throw new NotImplementedException();  
  17.      }  

In the above class we have implemented the IEnumerator interface which shows the above two methods and one property as we have already explained.

IEnumerable vs IEnumerator interface
 
While reading these two names, it's too confusion happen in mind so let us understand the difference between these two 
  1. IEnumerable and IEnumerator are both interfaces.
  2. IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator.
  3. if wants to implement enumerator logic in any of collection class, it need to be implement IEnumerable interface (either generic or non-generic).
  4. IEnumerable has just one method where as IEnumerator has two methods (MoveNext and Reset) and a property Current.

For our understanding we can say that  IEnumebale is a  box that contains IEnumerator inside it.

Let us learn it practically by creating one simple application as
 
Now create the project as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".

  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).

  3. Provide the Project name such as "IEnumerableInterface" or another as you wish and specify the location.

  4. Then right-click on Solution Explorer and select "Add New Item" then select Default.aspx page.

  5. Add One Button .
Now the Default.aspx source code will be as follows:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="IEnumerableInterface.Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.    
  11.     <asp:Button ID="Button1" runat="server" Text="GetList" OnClick="Button1_Click" />  
  12.     </form>  
  13. </body>  
  14. </html> 
Now open the Default.aspx.cs class file and create class named Customer with properties as
  1. public class Customer  
  2. {  
  3.   
  4.      private String _Name, _City;  
  5.      private long _Mobile;  
  6.      private double _Amount;  
  7.   
  8.      public String Name  
  9.      {  
  10.          get { return _Name; }  
  11.          set { _Name = value; }  
  12.      }  
  13.      public String City  
  14.      {  
  15.          get { return _City; }  
  16.          set { _City = value; }  
  17.      }  
  18.   
  19.      public long Mobile  
  20.      {  
  21.          get { return _Mobile; }  
  22.          set { _Mobile = value; }  
  23.      }  
  24.   
  25.   
  26.      public double Amount  
  27.      {  
  28.          get { return _Amount; }  
  29.          set { _Amount = value; }  
  30.      }  
  31. }  
In the above class file we have created properties of type string ,long and double which later on we will use along with IEnumerable generic interface
now create the Array of type customer class and assign the values to the each property as 
  1. Customer[] customers = new Customer[]  
  2. {  
  3.   
  4.     new Customer {Name="Vithal Wadje",City="Mumbai",Mobile=99999999999,Amount=89.45 },  
  5.     new Customer { Name = "Sudhir Wadje", City = "Latur", Mobile = 88888888888888888888, Amount =426.00 },  
  6.     new Customer { Name = "Anil", City = "Delhi", Mobile = 77777777777777777777, Amount = 5896.20 }                    
  7. }; 
Now in the above customer type array has different types of values we have assigned to the properties that we have created, now let us use the IEnumerable interface to loop through above collection as
  1. public IEnumerable<Customer> GetAllCustomer()  
  2. {  
  3.     return customers;                    

In the above example have assigned the Customer class collection to the IEnumerable to loop through each element, now we have already explained that IEnumerable interface collection can be iterated with the help of foreach loop over the IEnumerable interface collection, now let iterate through each item using IEnumerable interface as
  1. foreach (var cust in GetAllCustomer())  
  2. {      
  3.      Response.Write("Name: "+cust.Name + "<br> " +"City: " +cust.City + " <br> " +"Mobile "+cust.Mobile+"<br>
  4.      "+"Amount :" +cust.Amount.ToString("c") + "<br>"+"-----"+"<br>"); 
    }
In the above code ,we iterating on each item contained in the GetAllCustomer() collection IEnumerable interface method, now whole code will be look like as follows
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace IEnumerableInterface  
  5. {  
  6.     public partial class Default : System.Web.UI.Page  
  7.     {  
  8.         protected void Page_Load(object sender, EventArgs e)  
  9.         {  
  10.   
  11.         }  
  12.   
  13.   
  14.         protected void Button1_Click(object sender, EventArgs e)  
  15.         {  
  16.               
  17.             foreach (var cust in GetAllCustomer())  
  18.             {  
  19.   
  20.   
  21.               Response.Write("Name: "+cust.Name + "<br> " +"City: " +cust.City + " <br> "
  22.                         +"Mobile "+cust.Mobile+"<br> "+"Amount :" +cust.Amount.ToString("c") + "<br>"+"-----"+"<br>");                            
  23.             }        
  24.         }  
  25.     
  26.         public class Customer  
  27.         {  
  28.   
  29.             private String _Name, _City;  
  30.             private long _Mobile;  
  31.             private double _Amount;  
  32.   
  33.             public String Name  
  34.             {  
  35.                 get { return _Name; }  
  36.                 set { _Name = value; }  
  37.             }  
  38.             public String City  
  39.             {  
  40.                 get { return _City; }  
  41.                 set { _City = value; }  
  42.             }  
  43.   
  44.             public long Mobile  
  45.             {  
  46.                 get { return _Mobile; }  
  47.                 set { _Mobile = value; }  
  48.             }  
  49.   
  50.   
  51.             public double Amount  
  52.             {  
  53.                 get { return _Amount; }  
  54.                 set { _Amount = value; }  
  55.             }        
  56.         }  
  57.         Customer[] customers = new Customer[]  
  58.         {  
  59.   
  60.             new Customer {Name="Vithal Wadje",City="Mumbai",Mobile=99999999999,Amount=89.45 },  
  61.             new Customer { Name = "Sudhir Wadje", City = "Latur", Mobile = 88888888888888888888, Amount =426.00 },  
  62.             new Customer { Name = "Anil", City = "Delhi", Mobile = 77777777777777777777, Amount = 5896.20 }                    
  63.         };  
  64.   
  65.         public IEnumerable<Customer> GetAllCustomer()  
  66.         {      
  67.             return customers;                      
  68.         }  
  69.        
  70.     }  

Now run the application and click on GetList button the output will be as follows
 
 
Now from the above example it's clear that we can iterate through generic as well as non-generic collection with the help  IEnumerable interface.
 
Notes
  • Download the Zip file from the attachment for the full source code of the application.
Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.

Up Next
    Ebook Download
    View all
    Learn
    View all