Sobes.tech
Junior — Middle

Can you explain what the IEnumerable interface in programming language is?

sobes.tech AI

Answer from AI

IEnumerable is an interface in C# that defines the ability to iterate over a collection of objects.

It contains one method:

  • IEnumerator GetEnumerator() — returns an enumerator that allows sequential traversal of the collection's elements.

IEnumerable is used to implement the "iterator" pattern, enabling the use of foreach constructs to iterate over elements.

Example implementation:

class MyCollection : IEnumerable
{
    private int[] data = {1, 2, 3};

    public IEnumerator GetEnumerator()
    {
        for (int i = 0; i < data.Length; i++)
            yield return data[i];
    }
}

var collection = new MyCollection();
foreach(var item in collection)
{
    Console.WriteLine(item);
}

There is also a generic interface IEnumerable<T>, which provides type-safe iteration.

Can you explain what the IEnumerable interface in… - sobes.tech