Can somebody tell me why compiler thinks that break
is necessary after yield return
in the following code?
foreach (DesignerNode node in nodeProvider.GetNodes(span, node => node.NodeType != NDjango.Interfaces.NodeType.ParsingContext)) { switch (node.ErrorMessage.Severity) { case -1: case 0: continue; case 1: yield return new TagSpan<ErrorTag>(node.SnapshotSpan, new ErrorTag(PredefinedErrorTypeNames.Warning)); break; default: yield return new TagSpan<ErrorTag>(node.SnapshotSpan, new ErrorTag(PredefinedErrorTypeNames.SyntaxError)); break; } }
You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.
No this is not necessary. It will work: public static IEnumerable<int> GetDiff(int start, int end) { while (start < end) { yield return start; start++; } // yield break; - It is not necessary.
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.
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.
Because yield return is just syntactic sugar for an iterator generator, and you're not actually exiting any method. And C# doesn't allow fall-through in switch statements (and it doesn't look like you want it here anyway).
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