If I step through the following code the call to ReturnOne() is skipped.
static IEnumerable<int> OneThroughFive()
{
ReturnOne();
yield return 2;
yield return 3;
yield return 4;
yield return 5;
}
static IEnumerator<int> ReturnOne()
{
yield return 1;
}
I can only assume the compiler is stripping it out because what I’m doing is not valid. I’d like the ability to isolate my enumeration into various methods. Is this possible?
You’re not actually using the result of
ReturnOne. You’re calling the method, and ignoring the return value… which means you’d never actually see any of your code being run. You can do it like this:C# doesn’t (currently at least 🙂 have a sort of “yield all” construct.
The fact that you’re not getting to step into it has nothing to do with the fact that you’ve got a call within an iterator block – it’s just that until you start using the result of an iterator block, none of the code runs. That’s why you need to separate out argument validation from yielding. For example, consider this code:
You need to write it like this:
For more details, read chapter 6 of C# in Depth – which happens to be a free chapter in the first edition 🙂 Grab it here.