Alex Rivera | Logout

When to use the 'continue' keyword in C#

Asked 2011-11-01T21:25:09.720
38

Recently, I was going through an open-source project and although I have been developing for several years in .NET, I hadn't stumbled across the continue keyword before.

Question: What are some best practices or areas that would benefit from using the continue keyword? Is there a reason I might not have seen it previously?

Edit
Report

2 Answers

8

You should use it sparingly.

The best (= easiest to read) loops do not use break or continue, they are a kind of structured goto statements.

Having said that, 1 or even 2 break/continue statements won't make a loop unreadable, but it pays to make their use clear and to keep it simple.

answered 2011-11-01T21:28:08.533
2

Think of it as a "return", but only applicable to the context of a loop. A common example is a state machine, looping over all available input.

while(!SomeQueue.Empty)
{
    byte nextByte = SomeQueue.Dequeue();

    switch State:
    {
        case A:
            if(nextByte == Condition)
            {
                State = B;
            }
            else                
            {
                State = ParseError;
            }
            continue;
        case B:
            //Test nextByte
            State = C;
            continue;
        case C:
            //Test nextByte
            State = A;
            continue;
        case ParseError:
            //Do something for this condition
            State = A;
            continue;
}
answered 2011-11-01T21:32:44.490

Your Answer