#1,126 – Rewriting a Loop to Avoid continue Statement
June 26, 2014 7 Comments
The continue statement allows jumping to end of the body of a loop, skipping the rest of the code within the loop. Either the next iteration of the loop executes, or the code following the loop statement executes.
List<Dog> myDogs = new List<Dog> { new Dog {Name = "Kirby", Age = 5}, new Dog {Name = "Jack", Age = 17}, new Dog {Name = "Ruby", Age = 2} }; foreach (Dog d in myDogs) { if (d.Age > 15) continue; Console.WriteLine("{0} doing a trick", d.Name); d.DoATrick(); }
In most cases, you can rewrite the body of a loop and avoid using a continue statement by using an if statement. The end result is generally more readable.
foreach (Dog d in myDogs) { if (d.Age <= 15) { Console.WriteLine("{0} doing a trick", d.Name); d.DoATrick(); } }