System.Collections
Represents a type that is an iterable collection. This is the base interface for all generic and non-generic collection types in the .NET Framework.
Types that implement IEnumerable
can be enumerated by a for-each
loop (foreach
in C#, For Each
in Visual Basic). The IEnumerable
interface exposes the GetEnumerator
method, which returns an IEnumerator
object. The IEnumerator
object implements the basic enumeration capabilities, such as reading the next element and resetting the enumeration.
System.Collections.Generic.IEnumerable<T>
interface.
GetEnumerator()
IEnumerator
GetEnumerator()
Returns an enumerator that iterates through a collection.
// Assume 'myCollection' is an object that implements IEnumerable
IEnumerable myCollection = /* ... your collection ... */;
IEnumerator enumerator = myCollection.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
object currentItem = enumerator.Current;
// Process currentItem
Console.WriteLine(currentItem);
}
}
finally
{
// It's important to dispose the enumerator if it implements IDisposable
if (enumerator is IDisposable disposableEnumerator)
{
disposableEnumerator.Dispose();
}
}
The IEnumerable
interface is the fundamental interface for enabling collection iteration. It is the base interface for the IEnumerable<T>
generic interface.
When you use a for-each
loop in C#, the compiler translates the loop into code that uses the IEnumerable
and IEnumerator
interfaces.
A collection must implement IEnumerable
to be enumerated by the for-each
loop. This interface allows you to iterate over the elements of a collection without exposing its underlying representation.