Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C#

Alan Mattanó
PLUS
Alan Mattanó
Courses Plus Student 12,188 Points

What is the difference between break and continue in C# ?

I'm a bit lost here. In C#, what is the difference between using: break; and continue;

At the quiz exame, the code

while(true)
{    
    continue;
    Console.WriteLine("Ribbit")
}

Console.WriteLine("Croak");

Continue do not print Croak, why?

2 Answers

Continue is used to trigger the next iteration of the loop. In the example:

while(true)
{    
    continue;
    Console.WriteLine("Ribbit")
}
Console.WriteLine("Croak");

When you get to the continue you will then jump back up to the test in the While. So in this case you will never get to the Rabbit line and while(true) will never evaluate to false so you will never exit the loop to get to the Croak.

Break exits the loop and moves straight on to the line immediately after the loop.

--

Break will exit the loop completely, Continue will just skip the current iteration and then test the while statement again.

Alan Mattanó
Alan Mattanó
Courses Plus Student 12,188 Points

Thanks Bothxp so far. Perfect explanation, now is more clear also the purpose of the code!

If is possible, can you add 2 extra examples that help using both in common situations?

Andy Swinford
Andy Swinford
8,152 Points

Continue goes on to the next iteration of a loop whereas break ends the loop and moves on to the next step.