Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "yield break;" do in C#?

Tags:

yield

c#

.net

I have seen this syntax in MSDN: yield break, but I don't know what it does. Does anyone know?

like image 310
skb Avatar asked Oct 23 '08 23:10

skb


People also ask

What does yield do in C?

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 .

Does yield break a loop?

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.

What does yield break do Unity?

'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.

What is the benefit of yield C#?

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.


1 Answers

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.

like image 198
Damir Zekić Avatar answered Sep 19 '22 12:09

Damir Zekić