What's the use of yield break?

Miles Davis picture Miles Davis · Jan 31, 2009 · Viewed 25.8k times · Source

Possible Duplicate:
What does “yield break;” do in C#?

Can anyone see a use for the "yield break" statement that could not have been otherwise achieved by using "break" or "return".

This statement seems to be utterly useless. What's more, without this statement, the "yield return X" statement could have been simplified to "yield X", which much more readable.

What am I missing?

Answer

Cameron MacFarland picture Cameron MacFarland · Jan 31, 2009

To give a code example, say you want to write an iterator that returns nothing if the source is null or empty.

public IEnumerable<T> EnumerateThroughNull<T>(IEnumerable<T> source)
{
    if (source == null)
        yield break;

    foreach (T item in source)
        yield return item;
}

Without the yield break it becomes impossible to return an empty set inside an iterator.