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