Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# yield in nested method

Tags:

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?

like image 333
David Avatar asked Mar 23 '10 23:03

David


1 Answers

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:

static IEnumerable<int> OneThroughFive() {     foreach (int x in ReturnOne())     {         yield x;     }     yield return 2;     yield return 3;     yield return 4;     yield return 5; } 

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:

public IEnumerator<string> ReturnSubstrings(string x) {     if (x == null)     {          throw ArgumentNullException();     }     for (int i = 0; i < x.Length; i++)     {          yield return x.Substring(i);     } } ... ReturnSubstring(null); // No exception thrown 

You need to write it like this:

public IEnumerator<string> ReturnSubstrings(string x) {     if (x == null)     {          throw ArgumentNullException();     }     return ReturnSubstringsImpl(x); }  private IEnumerator<string> ReturnSubstringsImpl(string x) {     for (int i = 0; i < x.Length; i++)     {          yield return x.Substring(i);     } } 

For more details, read chapter 6 of C# in Depth - which happens to be a free chapter in the first edition :) Grab it here.

like image 108
Jon Skeet Avatar answered Sep 25 '22 07:09

Jon Skeet