List<T>.AddRange and the yield statement

Viewed 2224

I am aware that the yield keyword indicates that the method in which it appears is an iterator. I was just wondering how that works with something like List<T>.AddRange.

Let's use the below example:

static void Main()
{
    foreach (int i in MyInts())
    {
        Console.Write(i);
    }
}

public static IEnumerable<int> MyInts()
{  
    for (int i = 0; i < 255; i++)
    {
        yield return i;
    }
}

So in the above example after each yield, a value is returned in the foreach loop in Main and is printed to the console.

If we change Main to this:

static void Main()
{
    var myList = new List<int>();
    myList.AddRange(MyInts());
}

how does that work? Does AddRange get called for each int returned by the yield statement or does it somehow wait for all 255 values before adding the entire range?

3 Answers
Related