Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is break required after yield return in a switch statement?

Tags:

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;     } } 
like image 264
mfeingold Avatar asked Mar 01 '10 19:03

mfeingold


People also ask

Why do switch statements need breaks?

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.

Is yield break necessary?

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.

Does yield break return?

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 mean?

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.


1 Answers

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

like image 119
Matthew Flaschen Avatar answered Sep 21 '22 15:09

Matthew Flaschen