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#:
- yield break
- 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.