title: SqlDataReader to IEnumerable<T>
body: <p>I'm trying to write a method that retrieves a collection of type T for a query that returns a <strong>single column</strong> of values.</p>
  
  <p>What I've tried so far:</p>
  
  <pre><code>public static IEnumerable&lt;T&gt; ExecuteReader&lt;T&gt;(string query)
  {
      using (SqlConnection cn = new SqlConnection(conn.ConnectionString))
      {
          cn.Open();
          using (SqlCommand cmd = new SqlCommand(query, cn))
          {
              using (SqlDataReader reader = cmd.ExecuteReader())
              {
                 while (reader.Read()) 
                 { 
                     yield return (T)reader[0]; 
                 }
              }
          }
      }
  </code></pre>
  
  <p>Sample usage:</p>
  
  <pre><code>foreach (var dbname in ExecuteReader&lt;string&gt;("SELECT Name FROM sys.databases"))
  {
      //iterate db names
  }
  </code></pre>
  
  <p>Problem is now I'd like to add error handling to the code with <strong>try/catch</strong>, something like:</p>
  
  <pre><code>try
  {
      //my code
  }
  catch
  {
     //Error handling code
     return Enumerable.Empty&lt;T&gt;();
  }
  </code></pre>
  
  <p>However <strong>yield return is not compatible with try/catch</strong>.</p>
  
  <p>I've seen some alternatives on the web such as writing an extension for the IDataReader class but I feel like they could be outdated, so I'm open to suggestions or better ways to achieve this.</p>
  
  <p>EDIT: </p>
  
  <p>I feel like the answers are deviating from the question itself, maybe I didnt make myself clear. the <strong>try-catch</strong> or the <strong>yield</strong> <strong>are not relevant</strong> to me, this is simply a minor obstacle I found after writing my code. </p>
  
  <p><em>What I wanted to know is if this is the right way of populating a list from a datareader where a single column of generic type is retrieved.</em></p>