Is yield break equivalent to returning Enumerable<T>.Empty from a method returning IEnumerable<T>

Posted by Mike Two on Stack Overflow See other posts from Stack Overflow or by Mike Two
Published on 2010-03-16T18:52:49Z Indexed on 2010/03/16 19:01 UTC
Read the original article Hit count: 388

Filed under:

These two methods appear to behave the same to me

public IEnumerable<string> GetNothing()
{
    return Enumerable.Empty<string>();
}

public IEnumerable<string> GetLessThanNothing()
{
    yield break;
}

I've profiled each in test scenarios and I don't see a meaningful difference in speed, but the yield break version is slightly faster.

Are there any reasons to use one over the other? Is one easier to read than the other? Is there a behavior difference that would matter to a caller?

© Stack Overflow or respective owner

Related posts about c#