Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning empty collections

Tags:

c#

linq

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!

like image 992
Rob Avatar asked Dec 05 '08 21:12

Rob


3 Answers

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.

like image 103
Matthew Ruston Avatar answered Nov 12 '22 02:11

Matthew Ruston


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

like image 45
Amy B Avatar answered Nov 12 '22 03:11

Amy B


Even faster might be:

T[] e = {};
return e;
like image 1
leppie Avatar answered Nov 12 '22 03:11

leppie