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.

What is an IEnumerable interface in C#?

In C#, the 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 and the MoveNext () and Reset () methods.

Syntax Of IEnumerable Interface C#

The IEnumerable has the following syntax:

// Namespace: System.Collections
public interface IEnumerable

Key Points about IEnumerable 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 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 iterates 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 query.
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 throw 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.

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.

Thanks for visiting 🙂

Recommended Articles

    1. 10 Difference between interface and abstract class In C#
    2. Exception Handling in C#| Use of try, catch and finally block
    3. C# Enum | How To Play With Enum in C#?
    4. C# extension methods with examples
    5. Properties In C# with examples
    6. Generic Delegates in C# With Examples
    7. Constructors in C# with Examples
    8. C# Dictionary with Examples
    9. How to host your .net application to AWS EC2 Windows Server for free?

Leave a Reply