Rob
Rob

Reputation: 1983

Returning empty collections

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:

Thanks!

Upvotes: 5

Views: 3753

Answers (3)

Amy B
Amy B

Reputation: 110071

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

Upvotes: 4

Matthew Ruston
Matthew Ruston

Reputation: 4322

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.

Upvotes: 6

leppie
leppie

Reputation: 117220

Even faster might be:

T[] e = {};
return e;

Upvotes: 1

Related Questions