In the below article, the use of the “break” keyword with the “foreach” loop is discussed using C# language.
Exit Foreach Loop In C# Using the Break Keyword
“Loops” go through each element present in a collection until the condition is false and no more element is left in the collection. In the same manner, the “foreach” loop functions. Even when a certain condition is satisfied, it continues to iterate through each item. When a given condition is satisfied and we want to leave the loop right away, we use the “break” keyword to end the loop. The syntax of the break keyword is:
Let’s understand it with an example:
public class Break_example
{
public static void Main(string[] args)
{
string[] names={"Sarah", "James", "Alice", "Kevin","Hannah"};
foreach(string name in names){
Console.WriteLine ("The name the loop is going to check is: "+name);
if (name=="Kevin"){
Console.WriteLine ("The required name is: "+name);
}
}
}
}
In the above-stated code:
- There is a “System” namespace used.
- Then there is a class “Break_example” having a static “Main()” method.
- The names are then declared and stored in an array of type “string” called “names“.
- To check how the “foreach” loop works, a foreach loop is used and inside this loop an “if” condition is used which checks whether the name is “Kevin” or not. If the name is “Kevin” then the “The required name is: Kevin” statement will be printed.
Output:
Here we can see that even if the required name is found the loop continues to check other names as well. To terminate the loop when the name “Kevin” is found “break” keyword is used.
public class Break_example
{
public static void Main(string[] args)
{
string[] names={"Sarah", "James", "Alice", "Kevin","Hannah"};
foreach(string name in names){
Console.WriteLine ("The name the loop is going to check is: "+name);
if (name=="Kevin"){
Console.WriteLine ("The required name is: "+name);
break;
}
}
}
}
Now in this code, a break keyword is used inside the “if” statement to terminate the loop when the name “Kevin” is reached.
Output:
Here the output shows that when the name “Kevin” is reached the loop no longer checks the further names.
Conclusion
In C# “foreach” loop is used to iterate through a collection of objects. This loop will continue to check each item even if the required condition is met. To terminate the loop from traversing at a specific point a “break” keyword is used inside the loop.