find and solve || findandsolve.com
Please wait.....

What is IEnumerable in C#

In the C# programming language, IEnumerable is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows read-only access to a collection then a collection that implements IEnumerable can be used with a foreach statement.

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

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 given 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 the c# programming language, An IEnumerator interface will provide the ability to iterate through the given collection object by exposing the Current property, Reset, and MoveNext methods as shown below.


public interface IEnumerator
{
   bool MoveNext();
   object Current { get; }
   void 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.


Current 

The current property will return the current element of a list.


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


IEnumerable vs IEnumerator interface


IEnumerable IEnumerator 
IEnumerable is an interface.IEnumerator is an interface. 
It has just one method called GetEnumerator which method returns another type of an interfaceGetEnumerator method returns another type of an interface that interface is IEnumerator.
If you want to implement enumerator logic in any collection class, it needs to implement an IEnumerable interface (either generic or non-generic). The IEnumerator interface will provide the ability to iterate through the given collection object
IEnumerable has just one method.IEnumerator methods (MoveNext, and Reset) and a property Current.


Properties of IEnumerator Interface


public class Customer : IEnumerator
{
    public object Current
    {
       get { throw new NotImplementedException(); }
    }
    public bool MoveNext()
    {
       throw new NotImplementedException();
    }
    public void Reset()
    {
       throw new NotImplementedException();
    }
}


C# IEnumerable Example


using System;
using System.Collections;
namespace FindAndSolve
{
    public class Program
    {
       public static void Main(string[] args)
       {
          UserDetails[] userDetails = new UserDetails[3]{
          new UserDetails(1, "Sylvia", "Neupane"),
          new UserDetails(2, "Rahul", "Sharma"),
          new UserDetails(3, "Kala", "Neupane")
          };
          UsersInfo users = new UsersInfo(userDetails);
          foreach (var user in users)
          {
            Console.WriteLine(user.Id + ", " + user.FirstName + ", " + user.LastName);
          }
          Console.ReadLine();
       }
    }
    public class UserDetails
    {
       public UserDetails(int id, string firstName, string lastName)
       {
          this.Id = id;
          this.FirstName = firstName;
          this.LastName = lastName;
       }
       public int Id { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
    }
    //Implements IEnumerable Interface
    public class UsersInfo : IEnumerable
    {
       private UserDetails[] _userDetails;
       public UsersInfo(UserDetails[] userArray)
       {
          _userDetails = new UserDetails[userArray.Length];
          for (int i = 0; i < userArray.Length; i++)
          {
            _userDetails[i] = userArray[i];
          }
       }
       IEnumerator IEnumerable.GetEnumerator()
       {
          return (IEnumerator)GetEnumerator();
       }
       public UsersEnum GetEnumerator()
       {
          return new UsersEnum(_userDetails);
       }
    }
    // Implements IEnumerator Interface
    public class UsersEnum : IEnumerator
    {
       public UserDetails[] _userDetails;
       int currentIndex = -1;
       public UsersEnum(UserDetails[] list)
       {
         _userDetails = list;
       }
       public bool MoveNext()
       {
          currentIndex++;
          return (currentIndex < _userDetails.Length);
       }
       object IEnumerator.Current
       {
          get
          {
            return Current;
          }
       }
       public UserDetails Current
       {
         get
         {
           try
           {
              return _userDetails[currentIndex];
           }
           catch (IndexOutOfRangeException)
           {
              throw new InvalidOperationException();
           }
         }
       }
       public void Reset()
       {
          currentIndex = -1;
       }
    }
}


Output


1, Sylvia, Neupane

2, Rahul, Sharma

3, Kala, Neupane