Reputation: 973
Below the block of code which displays the numbers greater than 2 from MyList.
using System;
using System.Collections.Generic;
namespace CSharpBasics
{
internal class Program
{
private static List<int> MyList = new List<int>();
private static void Main(string[] args)
{
MyList.Add(1);
MyList.Add(2);
MyList.Add(3);
MyList.Add(4);
var test = FilterWithYield();
foreach (int i in test)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
private static IEnumerable<int> FilterWithYield()
{
foreach (int i in MyList)
{
if (i > 2)
{
yield return i;
}
}
}
}
}
Now when we set break-point to line foreach (int i in test)
, before executing the foreach
loop, test
variable will have the result from FilterWithYield()
. How it is possible?.My understanding is that until iteration starts IEnumerable method never executed.
Is I am missing anything here?
Thanks.
Upvotes: 1
Views: 835
Reputation: 1062550
test
is an enumerable - essentially an enumerator provider; when it is enumerated, the enumerator is fetched an iterated. Now; the enumerator and enumerable are usually be different, but the enumerable (test
) is still something, and that something still has some state that the IDE can probe. The IDE can detect enumerables, and iterates them for you to display the contents. This can actually be very inconvenient in some cases (where the sequence is non-repeatable). Hence the IDE did warn you about this before you clicked it - see "Expanding the Results View will enumerate the IEnumerable".
Upvotes: 2
Reputation: 578
Look at the warning - Expanding the Result View will enumerate the IEnumerable…
By looking at the results view, you are enumerating the values.
Upvotes: 6