Sunday 8 September 2019

.net - What does "yield break;" do in C#?




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


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...