In this blog post, we will see how to exit a for or a foreach loop in C#.

There can be a use case where you are checking a condition in a loop where you are iterating through a list or an array.

When this condition is met, you want to break from this loop and exit foreach loop.

This is very easy. We will use the break keyword in C# to achieve this.

 

 

 

 

Exit Foreach Loop Using break Keyword In C#

Let's see an example of breaking a foreach loop using the break keyword.

Let's say you have a list of colors or an array of colors and you are looping through the list and now you have to exit the foreach loop, you will use the break keyword to exit the loop.

Let's see this in action:

var listOfColors = new List { "orange", "red", "green", "pink" }; foreach (var color in listOfColors) { if (color == "green") { Console.WriteLine("Green color found. Exit the loop."); break; } Console.WriteLine("This color is: " + color); }

 

Result:

This color is: orange This color is: red Green color found. Exit the loop.

 

As you can see from the above result, we can see that the execution was stopped after the condition was met and we were able to exit the foreach loop using the break keyword.

 

 

Exit For Loop In C# - Break For Loop C#

Similar to how we break the execution in a foreach loop, we will apply the same theory to a for loop as well.

We will use the break keyword and will exit the for loop when our condition has been met.

Let's use the same example as above but in a for loop and try to exit the for loop.

var listOfColors = new List { "orange", "red", "green", "pink" }; for (int i = 0; i < listOfColors.Count; i++) { if (listOfColors[i] == "green") { Console.WriteLine("Green color found. Exit the loop."); break; } Console.WriteLine("This color is: " + listOfColors[i]); }

 

Result:

This color is: orange This color is: red Green color found. Exit the loop.

 

As we can see that we achieve the same result from a for loop as well.

We can now say that we can break for loop and we can exit a foreach loop using the break keyword in C#.