tags:

views:

306

answers:

3

Check out this test:

[TestFixture]
public class Quick_test
{
   [Test]
   public void Test()
   {
      Assert.AreEqual(0, GetByYield().Count());
      Assert.AreEqual(0, GetByEnumerable().Count());
   }

   private IEnumerable<string> GetByYield()
   {
      yield break;
   }

   private IEnumerable<string> GetByEnumerable()
   {
      return Enumerable.Empty<string>();
   }
}

When I write stub methods I generally use the Enumerable.Empty way of doing it. I stumbled across some old code I wrote where I did it the yield way.

This got me to wondering:

  • Which is more visually appealing to other developers?
  • Are there any hidden gotchas that would cause us to prefer one over the other?

Thanks!

+1  A: 

Even faster might be:

T[] e = {};
return e;
leppie
That bumps us from one-liners to two. Maybe this would be another alternative along that same thought? return new string[0];
Rob
+4  A: 

I would prefer any method that delivers the clearest meaning to the developer. Personally, I don't even know what the yield break; line is does, so returning 'Enumerable.Empty();` would be preferred in any of my code bases.

Matthew Ruston
I *do* know what yield break does, but I still think Enumerable.Empty() is a much clearer expression of intent.
Will Dean
+1  A: 

Enumerable.Empty : the documentation claims that it "caches an empty sequence". Reflector confirms. If caching behavior matters to you, there's one advantage for Enumerable.Empty

David B