Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

The non-generic IEnumerable interface

System.Collections.IEnumerable exposes iteration without specifying an element type through a generic parameter. Its GetEnumerator() method returns IEnumerator, and foreach reads elements through this contract.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

public interface IEnumerable
{
    System.Collections.IEnumerator GetEnumerator();
}

System.Collections.IEnumerable is a non-generic contract for iterating over elements. It declares one method: GetEnumerator(), returning System.Collections.IEnumerator. It exposes neither an element count nor an indexer.

Distinguish the sequence from its enumerator: IEnumerable provides an enumerator, whereas IEnumerator maintains the iteration position. MoveNext() advances to the next element and reports success; only then can you read the object-typed Current. Reading Current before the first successful advance or after iteration ends is not valid. Reset() need not be supported.

System.Collections.Generic.IEnumerable<T> specifies the element type and inherits from non-generic IEnumerable. When the type is known, generally prefer the generic version; the non-generic version is useful when interoperating with APIs requiring that contract. An explicit variable type in foreach, such as string, requires a valid conversion for every element; an incompatible element can cause InvalidCastException.

In the example, the array is accessed through IEnumerable, so value has type object even though the elements are strings. foreach handles advancing the enumerator. However, using foreach alone does not prove that this interface is implemented: C# also supports an appropriate GetEnumerator() pattern with MoveNext() and Current.

Examples

using System;
using System.Collections;

internal static class Program
{
    private static void Main()
    {
        IEnumerable values = new string[] { "Ada", "Lin" };

        foreach (object value in values)
        {
            Console.WriteLine(value);
        }
    }
}

Result

Ada
Lin

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources