When to use the 'continue' keyword in C#

Rion Williams picture Rion Williams · Nov 1, 2011 · Viewed 24.3k times · Source

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?

Answer

Anthony Pegram picture Anthony Pegram · Nov 1, 2011

You use it to immediately exit the current loop iteration and begin the next, if applicable.

foreach (var obj in list)
{
    continue;

    var temp = ...; // this code will never execute
}

A continue is normally tied to a condition, and the condition could usually be used in place of the continue;

foreach (var obj in list)
{ 
    if (condition)
       continue;

    // code
} 

Could just be written as

foreach (var obj in list)
{
    if (!condition)
    {
        // code
    }
}

continue becomes more attractive if you might have several levels of nested if logic inside the loop. A continue instead of nesting might make the code more readable. Of course, refactoring the loop and the conditionals into appropriate methods would also make the loop more readable.