Sumit Rayakwar
Sumit Rayakwar

Reputation: 175

Why is it necessary to implement IEnumerator when Implementing IEnumerable

Why is it necessary to implement IEnumerator when Implementing IEnumerable. Wherever I read its written only that it must happen but I just want the answer to the question of WHY.

Upvotes: 2

Views: 403

Answers (2)

Alan Yang
Alan Yang

Reputation: 66

From MICROSOFT document, it says "When you implement IEnumerable, you must also implement IEnumerator."

https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerator?view=netframework-4.7.2

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156524

The IEnumerable interface must implement a GetEnumerator() method, which returns an IEnumerator. In order to return an IEnumerator, there must be some implementation for you to return. Depending on your class, it may be possible to reuse an existing IEnumerator implementation, but it's also possible that your class has a custom way of being iterated over, in which case you'll need to create your own implementation of this interface.

There is a shortcut syntax available, however. You can use the yield return keyword in your GetEnumerator() method to let the C# compiler do the work of creating an IEnumerator implementation for you, based on some code that you provide inline. This example of a Collection class, for instance, implements it this way:

public class DaysOfTheWeek : IEnumerable
{
    private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

    public IEnumerator GetEnumerator()
    {
        for (int index = 0; index < days.Length; index++)
        {
            // Yield each day of the week. 
            yield return days[index];
        }
    }
}

Upvotes: 1

Related Questions