When to use the ‘continue’ keyword in C#

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)