Sunday, June 28, 2026

C# Using IEnumerator to loop throgh array

The foreach loop is shortcut for IEnumerator methods and properties. Since an array implements IEnumerable, we can use foreach loop.
class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        foreach (var number in numbers)
        {
            Console.Write(number + " ");
        }
        
        Console.WriteLine("\n----Second Approach-----");
        // since every array implements IEnumerable
        // and IEnumerable contains GetEnumerator()
        // we get Enumerator object
        // numbers.GetEnumerator().Current should not be used in while loop
        // because it will create a new instance of enumerator object in each iteration
        
        var enumerator = numbers.GetEnumerator();// create a single instance
        
        while (enumerator.MoveNext())
        {
            Console.Write(enumerator.Current + " ");
        }
    }
}
1 2 3 4 5
----Second Approach-----
1 2 3 4 5

No comments:

Post a Comment

Hot Topics