IEnumerable in C#

Background

 
Many times there is a need to loop through a collection of classes or lists which are anonymous types. IEnumerable interface is one of the best features of C# language which loops over the collection. Let us learn about it step by step so beginners also can understand.
 

What is IEnumerable in C#?

 
IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.
 

Key Points

  1. IEnumerable interface contains the System.Collections.Generic namespace.
  2. IEnumerable interface is a generic interface which allows looping over generic or non-generic lists.
  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 elements from the collection.

Methods of IEnumerator Interface

 
 IEnumerator is an interface which helps to get current elements from the collection, it has the 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 set to the next element and false if the enumerator has reached 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 a 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 can be confusing, 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 we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).
  4. IEnumerable has just one method whereas 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.
 
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 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 loop through above collection as:
  1. public IEnumerable<Customer> GetAllCustomer()  
  2. {  
  3.     return customers;                    

In the above example I 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 are iterating on each item contained in the GetAllCustomer() collection IEnumerable interface method, now the whole code will look like the following:
  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.         protected void Button1_Click(object sender, EventArgs e)
  12.         {
  13.             foreach (var cust in GetAllCustomer())
  14.             {
  15.               Response.Write("Name: "+cust.Name + "<br> " +"City: " +cust.City + " <br> "
  16.                         +"Mobile "+cust.Mobile+"<br> "+"Amount :" +cust.Amount.ToString("c") + "<br>"+"-----"+"<br>");
  17.             }
  18.         }
  19.         public class Customer  
  20.         {
  21.             private String _Name, _City;  
  22.             private long _Mobile;  
  23.             private double _Amount;  
  24.   
  25.             public String Name  
  26.             {  
  27.                 get { return _Name; }  
  28.                 set { _Name = value; }  
  29.             }  
  30.             public String City  
  31.             {  
  32.                 get { return _City; }  
  33.                 set { _City = value; }  
  34.             }  
  35.   
  36.             public long Mobile  
  37.             {  
  38.                 get { return _Mobile; }  
  39.                 set { _Mobile = value; }  
  40.             }
  41.             public double Amount  
  42.             {  
  43.                 get { return _Amount; }  
  44.                 set { _Amount = value; }  
  45.             }
  46.         }  
  47.         Customer[] customers = new Customer[]  
  48.         {  
  49.   
  50.             new Customer {Name="Vithal Wadje",City="Mumbai",Mobile=99999999999,Amount=89.45 },  
  51.             new Customer { Name = "Sudhir Wadje", City = "Latur", Mobile = 88888888888888888888, Amount =426.00 },  
  52.             new Customer { Name = "Anil", City = "Delhi", Mobile = 77777777777777777777, Amount = 5896.20 }
  53.         };  
  54.   
  55.         public IEnumerable<Customer> GetAllCustomer()  
  56.         {
  57.             return customers;
  58.         }
  59.     }  

Now run the application and click on GetList button and 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 suggestions then please contact me, even if you're a beginner.