c# foreach stop loop code example

Example 1: 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 2: get out of foreach statement c#

foreach (string s in sList)
{
    if (s.equals("ok"))
    {
        break; // get out of the loop
    }
}

Example 3: foreach c#

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");