IEnumerable Interface in C#-12 key points you should know about IEnumerable

In this article, we will discuss how to implement the IEnumerable interface in C# through several examples and code implementations.

IEnumerable in CSharp
IEnumerable in c#

What is an IEnumerable interface in C#?

IEnumerable interface is considered as the base interface for all the non-generic collections that can be enumerated by using the foreach statement. IEnumerable in C# is available in the System.Collections namespace. It contains a method called GetEnumerator, which returns the IEnumerator interface.
The IEnumerator interface provides the ability to loop through the collection by exposing the Current property, MoveNext, and Reset methods.

The IEnumerable interface has the following methods in C#:

Sr.NoMethod NameDescription
1GetEnumerator()It returns an enumerator that iterates through a collection.
2Cast<TResult>(IEnumerable)This method casts the elements of an IEnumerable to the specified type.
3OfType<<TResult>(IEnumerable)This method filters the elements of an IEnumerable based on a specified type.
4AsParallel(IEnumerable)It enables the parallelization of a query.
5AsQueryable(IEnumerable)It converts an IEnumerable to an IQueryable.
IEnumerable interface methods list.

Syntax Of IEnumerable Interface C#

The IEnumerable has the following syntax:

// Namespace: System.Collections
public interface IEnumerable

Key Points about IEnumerable Interface in C#:

  • IEnumerable is an interface available in System.Collections namespace
  • IEnumerable exposes an enumerator, which supports a simple iteration over a non-generic collection using a foreach statement in C#.
  • IEnumerator interface provides the ability for non-generic collections to loop through the collection by exposing the Current property and MoveNext() and Reset() methods.
  • We can use IEnumerable when we need read-only access to the collection.
  • IEnumerable can be used to iterate when the records are already loaded into the memory.
  • We can use both IEnumerable and IEnumerator interfaces in case we want to iterate over the custom collection class in C#.
  • An IEnumerable interface can be used with the Linq query expression.
  • IEnumerable is best suitable for working with in-memory collections like Array, List, Stack, Queue, Dictionary, etc.
  • IEnumerable is not suitable for pagination as it read the collection in forward-only mode.
  • IEnumerable doesn’t support lazy loading.
  • An IEnumerable interface does not support custom queries.
image IEnumerable in C#
IEnumerable in C#

MoveNext() and Reset() Methods of IEnumerator Interface In C#

IEnumerator.MoveNext

public bool MoveNext ();
 MoveNext()  method of IEnumerator interface returns true if the enumerator was successfully advanced to the next element of the collection. It returns false if the enumerator has passed the end of the collection.

IEnumerator.Reset

public void Reset ();

The Reset() method of the IEnumerator interface is used to set the enumerator to its initial position, which is the position before the first item in the collection.

If any type of changes is made to the collection, such as adding, modifying, or deleting items, the reset behavior is undefined.

InvalidOperationException can be thrown if the collection was modified after the enumerator was created.

IEnumerator.Current Property Of IEnumerator Interface

public object Current { get; }

The current property of the IEnumerator interface is used to get the element at the current position of the enumerator in the collection.

C# IEnumerable Examples

The IEnumerable interface exposes an enumerator that supports a simple iteration over non-generic collections.
Implementing the IEnumerable and IEnumerator interfaces in the following code examples shows how to iterate a custom collection in the best possible way.

C# IEnumerable – Example #1

In the following code snippet, we’ll use the IEnumerable interface to store a series of integer variables, and then we’ll print numbers greater than 5.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace IEnumerableInterfaceDemo
{
    class Program
    {
        static void Main()
        {
            IEnumerable<int> Items = from values in Enumerable.Range(1, 10)
                                      where values > 5 select values;
            foreach (int item in Items)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();

        }
    }   
}
// Output:
// 6
// 7
// 8
// 9
// 10

C# IEnumerable-Create custom collection – Example #2

Let’s implement the IEnumerable and IEnumerator interfaces to support iterating custom collections.
The following is a code snippet for a custom collection.

using System;
using System.Collections;
namespace IEnumerableInterfaceDemo
{   //Author: Shekh Ali

    // EmployeeInfo class is a business object.
    public class EmployeeInfo
    {
        public int Id { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public EmployeeInfo(int id, string firstName, string lastName)
        {
            this.Id = id;
            this.firstName = firstName;
            this.lastName = lastName;
        }

    }

    // This class implements IEnumerable so that it can be used
    // with Foreach loop.
    public class CustomEmployeeCollection : IEnumerable
    {
        public EmployeeInfo[] empInfo;
        public CustomEmployeeCollection(EmployeeInfo[] empArray)
        {
            empInfo = new EmployeeInfo[empArray.Length];
            for (int index = 0; index < empArray.Length; index++)
            {
                empInfo[index] = empArray[index];
            }
        }

        // Implementation for the GetEnumerator method.
        IEnumerator IEnumerable.GetEnumerator()
        {
            return (IEnumerator)GetEnumerator();
        }
        public EmployeeEnumerator GetEnumerator()
        {
            return new EmployeeEnumerator(empInfo);
        }
    }

    public class EmployeeEnumerator : IEnumerator
    {

        int currentPosition = -1;
        public EmployeeInfo[] empInfo;
        public EmployeeEnumerator(EmployeeInfo[] empInfo)
        {
            this.empInfo = empInfo;
        }
       
        
        public bool MoveNext()
        {
            currentPosition++;

            if (currentPosition < empInfo.Length)
            {
                return true;
            }

            return false;
        }    
        object IEnumerator.Current => Current;
        public EmployeeInfo Current => empInfo[currentPosition];
        void IEnumerator.Reset() => currentPosition = 0;
        
    }

    class Program
    {
        static void Main()
        {
            EmployeeInfo[] employeeInfo = new EmployeeInfo[3]
           {
                new EmployeeInfo(101, "Shekh", "Ali"),
                new EmployeeInfo(102, "Denni", "Thomas"),
                new EmployeeInfo(103, "Mark", "Adams")
           };

            CustomEmployeeCollection customEmployeeCollection = new 
            CustomEmployeeCollection(employeeInfo);
            Console.WriteLine($"ID      FirstName   LastName");
            foreach (var employee in customEmployeeCollection)
            {
           Console.WriteLine($"{employee.Id}      {employee.firstName}      {employee.lastName} ");
            }
            Console.ReadLine();

        }
    }
}

CustomCollection using IEnumerable Interface
The output of the above program.

Q: What is the purpose of the IEnumerable interface in C#?

Ans: An interface called IEnumerable defines a single method called GetEnumerator() that returns an IEnumerator interface. All non-generic collections that may be enumerated use it as their base interface.
This is useful for read-only access to collections using the foreach loop.

Q: What differentiates a list from an IEnumerable in C#?

Ans: An important difference between IEnumerable and List (besides that one is an interface and the other is a concrete class) is that IEnumerable is read-only and List is not. So if you want the ability to make any kind of permanent modification (addition and deletion) to your collection, you need a List.

Q: Which is faster IEnumerable or IQueryable?

Ans: IQueryable retrieves records based on filters. IQueryable does all filtering at once and returns the results, making it faster than IEnumerable, which loads data into memory and then performs filtering one at a time.

Q: When is it appropriate to use an IEnumerable?

Ans: IEnumerable is the best way to query data from in-memory collections such as Lists and Arrays. IEnumerable cannot be used to add or remove items from a list. You can use IEnumerable to count the number of items in a collection after iterating in a foreach loop.

Conclusion:

In this article, we discuss how to implement the IEnumerable and IEnumerator interfaces through various examples. In addition, we learned how to iterate a custom collection using the IEnumerable and IEnumerator interfaces.

Hope you like this article, if you have any questions, please ask your questions in the comment section.

References: MSDN- IEnumerable Interface

Recommended Articles:

Leave a Comment