Alex Rivera | Logout

What's the use of yield break?

Asked 2009-01-31T00:13:50.913
42

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?

Edit
Report

2 Answers

10

yield break specifies that the method should stop returning results. "return" by itself would not be good enough, or could even lead to a bug, because the return type of the method has to be IEnumerable.

I am not sure why the return keyword is also needed. My best guess would be that it helps make the intention of the statement a little clearer.

If you are interested, this article explains what yield is doing behind the scenes

Behind the scenes of the C# yield keyword

answered 2009-01-31T00:29:57.807
3

It is illegal to use a return statement in an iterator block. Moreover, the break statement could serve a dual purpose within an iterator block if it were to be allowed to affect the iteration: it could be used to break out of a loop or out of a switch, and it could be used to break out of the whole iteration.

yield return and yield break and are two keywords in and of themselves, and they both seem to be necessary.

answered 2009-01-31T00:56:08.347

Your Answer