Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we debug a method with yield return for the following code? [duplicate]

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?

like image 910
iCode Avatar asked Feb 17 '16 02:02

iCode


1 Answers

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();
like image 134
Sergey Kalinichenko Avatar answered Sep 19 '22 16:09

Sergey Kalinichenko