I have seen this syntax in MSDN: yield break
, but I don't know what it does. Does anyone know?
The yield keyword tells the compiler that the method in which it appears is an iterator block. yield return <expression>; yield break; The yield return statement returns one element at a time. The return type of yield keyword is either IEnumerable or IEnumerator .
In a normal (non-iterating) method you would use the return keyword. But you can't use return in an iterator, you have to use yield break . In other words, yield break for an iterator is the same as return for a standard method. Whereas, the break statement just terminates the closest loop.
'yield break' is like the reset button. It exits the function and makes it so that we start from the beginning of the function the next time it's called.
The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created so it's more efficient. The yield operator allows the creation of items as it is demanded. That's a good reason to use it.
It specifies that an iterator has come to an end. You can think of yield break
as a return
statement which does not return a value.
For example, if you define a function as an iterator, the body of the function may look like this:
for (int i = 0; i < 5; i++) { yield return i; } Console.Out.WriteLine("You will see me");
Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.
Or like this with yield break
:
int i = 0; while (true) { if (i < 5) { yield return i; } else { // note that i++ will not be executed after this yield break; } i++; } Console.Out.WriteLine("Won't see me");
In this case the last statement is never executed because we left the function early.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With