dotnetdev dotnetdev - 5 days ago 5
C# Question

Using return to exit a loop?

If I write a for, do, or while loop, is it possible to come out of this with the return keyword?

Eg:

class BreakTest
{
public static void Main()
{
for (int i = 1; i <= 100; i++)
{
if (i == 5)
**return;**
Console.WriteLine(i);
}
}
}


I know return can be used to exit if statements so I am curious about this as I have never tried it (and can't access my software to write the code to test this).

Answer

return will exit the current method (Main in your example). Use break to exit the loop.

Comments