IEnumerable in C#

In c#, IEnumerable is an interface, and it is useful to enable an iteration over non-generic collections, and it is available with System.Collections namespace.

 

Generally, the IEnumerable interface will represent an object that can be enumerated and it’s a base interface for all non-generic collections that can enumerate. The IEnumerable interface class will contain the code as shown below.

 

public interface IEnunmerable
{
IEnumerator GetEnumerator();
}

The IEnumerable will contain a single GetEnumerator() method, and it will return an IEnumerator object.

C# IEnumerator Interface

In c#, the IEnumerator interface will provide the ability to iterate through the given collection object by exposing Current property, MoveNext, and Reset methods like as shown below.

 

public interface IEnumerator
{
   bool MoveNext();
   object Current { get; }
   void Reset();
}

Here, the MoveNext() method will return a Boolean value to indicate whether we reach the end of the list or not, and the Current property will return the current element of a list. The Reset() method will reset an enumerator to the initial position to re-iterate the list from the beginning.

 

To enable an iteration over the custom collection classes, you need to implement both IEnumerable and IEnumerator interfaces.

 

In c#, all the collection elements such as queue, stack, list, dictionary, etc., are enumerable because they already implemented an IEnumerable interface. So, we are able to iterate over the items in collections using a foreach loop.

C# IEnumerable Example

Following is the example of enabling an iteration over the custom collection by implementing IEnumerable and IEnumerator interfaces.

 

using System;
using System.Collections;

namespace TutlaneExamples
{
    class Program
    {
       static void Main(string[] args)
       {
          UserInfo[] uInfo = new UserInfo[3]{
          new UserInfo(1, "Suresh", "Chennai"),
          new UserInfo(2, "Rohini", "Guntur"),
          new UserInfo(3, "Trishika", "Guntur")
          };
          Users users = new Users(uInfo);
          foreach (var user in users)
          {
            Console.WriteLine(user.Id + ", " + user.Name + ", " + user.Location);
          }
          Console.ReadLine();
       }
    }
    public class UserInfo
    {
       public UserInfo(int id, string name, string location)
       {
          this.Id = id;
          this.Name = name;
          this.Location = location;
       }
       public int Id { get; set; }
       public string Name { get; set; }
       public string Location { get; set; }
    }
    //Implements IEnumerable Interface
    public class Users : IEnumerable
    {
       private UserInfo[] _user;
       public Users(UserInfo[] uArray)
       {
          _user = new UserInfo[uArray.Length];
          for (int i = 0; i < uArray.Length; i++)
          {
            _user[i] = uArray[i];
          }
       }
       IEnumerator IEnumerable.GetEnumerator()
       {
          return (IEnumerator)GetEnumerator();
       }
       public UsersEnum GetEnumerator()
       {
          return new UsersEnum(_user);
       }
    }
    // Implements IEnumerator Interface
    public class UsersEnum : IEnumerator
    {
       public UserInfo[] _user;
       int currentIndex = -1;
       public UsersEnum(UserInfo[] list)
       {
         _user = list;
       }
       public bool MoveNext()
       {
          currentIndex++;
          return (currentIndex < _user.Length);
       }
       object IEnumerator.Current
       {
          get
          {
            return Current;
          }
       }
       public UserInfo Current
       {
         get
         {
           try
           {
              return _user[currentIndex];
           }
           catch (IndexOutOfRangeException)
           {
              throw new InvalidOperationException();
           }
         }
       }
       public void Reset()
       {
          currentIndex = -1;
       }
    }
}

If you observe the above example, we implemented both IEnumerable and IEnumerator interfaces to enable an iteration over non-generic collection object (Users).

 

After implementing IEnumerable and IEnumerator interfaces, we are able to iterate through Users object using a foreach loop.

 

When we execute the above example, we will get the result as shown below.

 

1, Suresh, Chennai
2, Rohini, Guntur
3, Trishika, Guntur

This is how you can use the IEnumerable interface in c# to enable an iteration over non-generic collection items based on our requirements.

C# IEnumerable Overview

Following are the important points which we need to remember about IEnumerable in c#.

 

  • IEnumerable is an interface, and it is useful to enable an iteration over non-generic collections.
  • IEnumerable is available with System.Collections namespace.
  • IEnumerator interface will provide the ability to iterate through the given collection object by exposing Current property and MoveNext and Reset methods.
  • To enable an iteration over the custom collection classes, you need to implement both IEnumerable and IEnumerator interfaces.