Return an empty IEnumerable<T> from a yield iterator

This question came up the other day:

How do I return an empty IEnumerable<T> from a method using the C# yield keyword?

There are actually two ways of doing this. Both, admittedly, are not the most intuitive things in C#:

  1. yield break
  2. Do not return anything

yield break terminates the iterator. For example, the following iterator returns an IEnumerable<string> containing a single element ‘Value’.

public static IEnumerable<string> GetEnumerator(bool condition)
{
    if (condition)
    {
        yield return "Value";
    }

    yield break;
}

That same method above can actually be rewritten without even specifying yield break and simply not returning anything outside of the condition:

public static IEnumerable<string> GetEnumerator(bool condition)
{
    if (condition)
    {
        yield return "Value";
    }
}

This is perfectly legal; as long there is at least one yield return in a method, the C# compiler will not require you to return a value on all code paths.

Published Monday, December 22, 2008 7:00 AM by David Kean
Filed under:

Comments

Monday, December 22, 2008 11:48 AM by Steven

# re: Return an empty IEnumerable<T> from a yield iterator

'return new string[0];' will do just fine ;-)

Yes that works well in the situation where you aren't using yield, however, you can't return that when you are using yield in a method.
Tuesday, December 23, 2008 3:12 AM by Bruce Boughton

# re: Return an empty IEnumerable<T> from a yield iterator

yield break seems to be the most readable approach to me. It does exactly what is says: breaks straight away, without yielding any items.

Sunday, December 28, 2008 10:13 AM by Yoann. B

# re: Return an empty IEnumerable<T> from a yield iterator

Great ! Thanks.

Sunday, December 28, 2008 5:19 PM by #.think.in

# #.think.in infoDose #13 (22nd Dec - 26th Dec)

#.think.in infoDose #13 (22nd Dec - 26th Dec)