Declaration
public interface IEnumerable<out T> : IEnumerable
Represents a zero-based, ordered collection of items that can be accessed by index and is the base interface for collections that can be enumerated.
Remarks
The IEnumerable<T>
interface is the base interface from which all generic collection types derive. It provides the core functionality for iterating over a collection by using a foreach
statement.
When you iterate through a collection that implements IEnumerable<T>
, you are using the IEnumerable<T>
interface. The foreach
statement simplifies the process of iterating through the collection.
Members
Methods
GetEnumerator()
IEnumerator<T> GetEnumerator();
Returns an enumerator that iterates through the collection.
Return value: An IEnumerator<T>
object that can be used to iterate through the collection.
Example
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
// Using foreach loop (implicitly uses GetEnumerator)
foreach (var name in names)
{
Console.WriteLine(name);
}
// Explicitly using GetEnumerator
using (IEnumerator<string> enumerator = names.GetEnumerator())
{
while (enumerator.MoveNext())
{
string currentName = enumerator.Current;
Console.WriteLine($"Explicit: {currentName}");
}
}
}
}
Inheritance
IEnumerable<T>
implements IEnumerable
.
Implements
Interface | Description |
---|---|
IEnumerable |
Provides access to the GetEnumerator method, which supports a simple iteration over a non-generic collection. |