c# stop while loop code example
Example 1: c sharp exit while loop
// To forcibly exit a while loop use 'break'
while (true)
{
// Do something
if (conditional)
{
break;
}
}
Example 2: c# stop loop
while (playerIsAlive)
{
// this code will keep running
if (playerIsAlive == false)
{
// eventually if this stopping condition is true,
// it will break out of the while loop
break;
}
}
// rest of the program will continue
Example 3: while loop in c#
int i = 0;
while (i < 10)
{
Console.WriteLine("Value of i: {0}", i);
i++;
}
Example 4: c# stop loop in method
/* There is another way to break out of a loop if you use
the return command inside a method/function */
class MainClass {
public static void Main (string[] args) {
UnlockDoor();
// after it hits the return statement,
// it will move on to this method
PickUpSword();
}
static bool UnlockDoor()
{
bool doorIsLocked = true;
// this code will keep running
while (doorIsLocked)
{
bool keyFound = TryKey();
// eventually if this stopping condition is true,
// it will break out of the while loop
if (keyFound)
{
// this return statement will break out of the entire method
return true;
}
}
return false;
}
}