title: Proper use of 'yield return'
body: <p>The <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield" rel="noreferrer">yield</a> keyword is one of those <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/" rel="noreferrer">keywords</a> in C# that continues to mystify me, and I've never been confident that I'm using it correctly.</p>
  
  <p>Of the following two pieces of code, which is the preferred and why?</p>
  
  <p><strong>Version 1:</strong> Using yield return</p>
  
  <pre><code>public static IEnumerable&lt;Product&gt; GetAllProducts()
  {
      using (AdventureWorksEntities db = new AdventureWorksEntities())
      {
          var products = from product in db.Product
                         select product;
  
          foreach (Product product in products)
          {
              yield return product;
          }
      }
  }
  </code></pre>
  
  <p><strong>Version 2:</strong> Return the list</p>
  
  <pre><code>public static IEnumerable&lt;Product&gt; GetAllProducts()
  {
      using (AdventureWorksEntities db = new AdventureWorksEntities())
      {
          var products = from product in db.Product
                         select product;
  
          return products.ToList&lt;Product&gt;();
      }
  }
  </code></pre>