title: Yield return inside usings
body: <p>If I recall correctly that when I used yield inside <code>using SqlConnection</code> blocks I got runtime exceptions.</p>
  
  <pre><code>using (var connection = new SqlConnection(connectionString))
  {
      var command = new SqlCommand(queryString, connection);
      connection.Open();
  
      SqlDataReader reader = command.ExecuteReader();
  
      // Call Read before accessing data.
      while (reader.Read())
      {
          yield reader[0];
      }
  
      // Call Close when done reading.
      reader.Close();
  }
  </code></pre>
  
  <p>Those problems were solved when I replaced <code>yield</code> by a List where I added items each iteration.</p>
  
  <p>The same problem didn't happen yet to me when inside <code>using StreamReader</code> blocks</p>
  
  <pre><code>using (var streamReader = new StreamReader(fileName))
  {
      string line;
      while ((line = streamReader.ReadLine()) != null)
      {
          yield return line;
      }
  }
  </code></pre>
  
  <p>Is there any explanation why Exceptions happened in the former case and not in the latter? Is this construction advisable?</p>
  
  <p><strong>EDIT</strong> To get the error (early disposal) that I did in the past you should call the first method below:</p>
  
  <pre><code>IEnumerable&lt;string&gt; Read(string fileName)
  {
      using (var streamReader = new StreamReader(fileName))
      {
          return Read(streamReader);
      } // Dispose will be executed before ReadLine() because of deffered execution
  }
  
  IEnumerable&lt;string&gt; Read(StreamReader streamReader)
  {
      string line;
      while ((line = streamReader.ReadLine()) != null)
      {
          yield return line;
      }
  }
  </code></pre>
  
  <p>The same error can be achieved with other ways of deferring execution, such as <code>System.Linq.Enumerable.Select()</code></p>