Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't step into iterator block whilst debugging (C#)

I'm trying to debug my code which is being executed from a unit test project, but when I try to step into a method, it just passes straight onto the next line and the breakpoint inside that method isn't hit. The method is on a class which is in a different project, but all the code is built in debug mode and I've tried cleaning and rebuilding the solution with no joy.

However, this has only happened since I added an iterator block to the method. When I remove it and rebuild, I can step in fine. Weird?

I am using Visual Studio 2010 Beta 1, could this just be a bug?

like image 761
Charlie Avatar asked Jun 21 '09 14:06

Charlie


2 Answers

Iterator blocks use deferred execution - meaning: until you actually start iterating over the data, nothing is executed.

So: has the data been iterated? Is anything looping over the values? If you need to add validation logic that runs as early as possible, you currently need two methods:

public static IEnumerable<int> GetNumbers(int from, int to) {
    // this validation runs ASAP (not deferred)
    if (to < from) throw new ArgumentOutOfRangeException("to");
    return GetNumbersCore(from, to);
}
private static IEnumerable<int> GetNumbersCore(int from, int to) {
    // this is all deferred
    while (from <= to) {
        yield return from++;
    }
}
like image 108
Marc Gravell Avatar answered Oct 24 '22 19:10

Marc Gravell


Marc is correct. The method is deferred executed and you can't step into the method until the iterator actually executes.

When I need to debug an iterator block in a unit test I do the following. Assume the method is called GetStuff.

[TestMethod]
public void TestGetStuff() {
  var obj = GetStuffObje();
  var list = obj.GetStuff().ToList();
}

The .ToList() call will force the iterator to execute to completion. I then set a breakpoint inside the GetStuff method and start a debugging session

like image 41
JaredPar Avatar answered Oct 24 '22 17:10

JaredPar