somethingSomething
somethingSomething

Reputation: 860

What happens in the foreach loop, which outputs the values of an array?

I'm learning C and C#, this question is for C#. I have a instance of a class and I use a foreach loop to iterate through the values of "string[] days", but how does this happen? The class has a method which is GetEnumerator() and a array which is string[] days, but how does a instance of the class evaluate to the values of the string?

Here is the code:

static void Main()
{ 
    DaysOfTheWeek days = new DaysOfTheWeek();

    foreach (string day in days)
    {
        Console.Write(day + " ");
    }
    // Output: Sun Mon Tue Wed Thu Fri Sat
    Console.ReadKey();
 }

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: 0

Views: 119

Answers (3)

ChrisK
ChrisK

Reputation: 1218

Your DaysOfTheWeek implements the interface IEnumerable. If you look at theforeach-documentation, you see that foreach works with something that implements IEnumerable (technically it works with everything that has an appropriate GetEnumerator method, see comments below).

When you implement IEnumerable you basically promise, that you also implement a (public) method called GetEnumerator. Since the foreach knows that this method is there, it will use it to iterate over/obtain your string values.

Upvotes: 1

kevin
kevin

Reputation: 2213

First thing first, you do not have to write your own enumerator because every array (of ANY type) has an enumerator built in for you. So you would do:

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

    foreach(var day in days){
        Console.WriteLine(day);
    }
}

Any class that implements the IEnumerable has a GetEnumerator() method, which returns a class that enumerates through the collection. The compiler translates the foreach loop for you using the Enumerator workflow. In short the compiler translates your code to something like:

private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
var enumerator = days.GetEnumerator();
while(enumerator.MoveNext()){
    Console.WriteLine(enumerator.Current);
}

Check out more about how enumerators work on the MSDN documentation.

Upvotes: 1

user3014562
user3014562

Reputation:

The foreach loop calls automatically the GetEnumerator method, which yields the days (strings).

Upvotes: 1

Related Questions