Following is my code:
class Program {
static List<int> MyList;
static void Main(string[] args) {
MyList = new List<int>() { 1,24,56,7};
var sn = FilterWithYield();
}
static IEnumerable<int> FilterWithYield() {
foreach (int i in MyList) {
if (i > 3)
yield return i;
}
}
}
I have a break point in FilterWithYield
Method but its not at all hitting the break point. I have one break at the calling point i.e var sn = FilterWithYield();
Control hits this point and shows the result correctly in debugging window. But why isn't the control stopping in the FilterWithYield method?
One more question. I read that yield returns data to the caller..if that is so if changed return type of FilterWithYield method to int it through error.Does the yield key word always need IEnumerable<T>
as return type?
You can debug the method. The problem is, the code that you are trying to reach is never executed.
IEnumerable
methods with yield return
produce code that makes your sequence lazily, as you go through enumeration. However, when you do this
var sn = FilterWithYield();
you prepare to enumerate the sequence, but you do not start enumerating it.
If, on the other hand, you add a foreach
loop or call ToList()
on the result, your breakpoint would get hit:
foreach (var n in FilterWithYield()) {
Console.WriteLine(n);
}
or
var sn = FilterWithYield().ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With