IEnumerator<T> Interface
Represents an enumerator for a generic collection.
Syntax
public interface IEnumerator<out T> : System.Collections.IEnumerator, System.IDisposable
Type Parameters
-
T
The type of objects to enumerate. The enumerator is covariant.
Members
Methods
Current
T Current { get; }
Gets the element in the collection at the current position of the enumerator.
Dispose
void IDisposable.Dispose()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
This method is part of the IDisposable interface.
MoveNext
bool MoveNext()
Advances the enumerator to the next element of the collection.
Returns:
true
if the enumerator was successfully advanced to the next element; false
if the enumerator has passed the end of the collection.
Reset
void Reset()
Sets the enumerator to its initial position before the first element in the collection.
Remarks
The T
type parameter is used to specify the type of objects to enumerate. This generic interface inherits from System.Collections.IEnumerator
and System.IDisposable
.
When you use a for each
loop (For Each
in Visual Basic) to iterate through a collection, the compiler generates code that uses this interface.
The T
in IEnumerator<T>
is declared as out
, which means the interface is covariant. Covariance allows you to use a more derived type than the one originally specified. For example, you can assign an IEnumerator<string>
to an IEnumerator<object>
.
Examples
using System;
using System.Collections.Generic;
public class Example
{
public static void Main(string[] args)
{
List<string> names = new List<string>() { "Alice", "Bob", "Charlie" };
// Using foreach loop (compiler uses IEnumerator internally)
Console.WriteLine("Using foreach:");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("\nUsing IEnumerator manually:");
// Manually using IEnumerator
using (IEnumerator<string> enumerator = names.GetEnumerator())
{
while (enumerator.MoveNext())
{
string currentName = enumerator.Current;
Console.WriteLine(currentName);
}
}
}
}