title: C# Iterator can not contain return statement
body: <p>I'm trying implement python like range data struct in c# witch implements <code>IEnumerable&lt;int&gt;</code>.</p>
  
  <p>My <code>Range</code> struct has 3 integer fields: <code>start, stop, step</code>.</p>
  
  <p>I also write <code>RangeIterator</code> data struct which implements <code>IEnumerator&lt;int&gt;</code> and accepts range object to it's constructor. Because I want to decouple <em>range iterator</em> object and range object. </p>
  
  <p>And in <code>Range</code> struct I write:    </p>
  
  <pre><code>    public IEnumerator&lt;int&gt; GetEnumerator()
      {
          return new RangeIterator(ref this);
      }
  </code></pre>
  
  <p>Everything works fine.</p>
  
  <p>But there is some cases which range should not be generate number due to <code>start, stop, step</code> parameters. And I want to check if it should generate number(s) before creating <code>RangeIterator</code> object for optimization.</p>
  
  <p>I changed code to:</p>
  
  <pre><code>        public IEnumerator&lt;int&gt; GetEnumerator()
          {
              if (!ShouldGenerate)
              {
                  yield break;
              }
              return new RangeIterator(ref this);
          }
  </code></pre>
  
  <p>But it says </p>
  
  <blockquote>
    <p>Iterator can not contain return statement</p>
  </blockquote>
  
  <p>How can I avoid creating <code>RangeIterator</code> in this situation?</p>
  
  <p>I'm sorry, English is not my native language.</p>
  
  <p>Edit 1:</p>
  
  <p>I found error reason in <a href="https://stackoverflow.com/a/23391246/4791963">this answer</a> but I haven't any idea how to avoid creating enumerator object if it isn't needed.</p>