How do I exit a foreach loop in C#?

C#Foreach

C# Problem Overview


foreach (var name in parent.names)
{
    if name.lastname == null)
    {
        Violated = true;
        this.message = "lastname reqd";
    }

    if (!Violated)
    {
        Violated = !(name.firstname == null) ? false : true;
        if (ruleViolated)
            this.message = "firstname reqd";
    }
}

Whenever violated is true, I want to get out of the foreach loop immediately. How do I do it?

C# Solutions


Solution 1 - C#

Use break.


Unrelated to your question, I see in your code the line:

Violated = !(name.firstname == null) ? false : true;

In this line, you take a boolean value (name.firstname == null). Then, you apply the ! operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null). Why not use that, as in:

Violated = (name.firstname == null);

Solution 2 - C#

Just use the statement:

break;

Solution 3 - C#

Use the break keyword.

Solution 4 - C#

Look at this code, it can help you to get out of the loop fast!

foreach (var name in parent.names)
{
   if (name.lastname == null)
   {
      Violated = true;
      this.message = "lastname reqd";
      break;
   }
   else if (name.firstname == null)
   {
      Violated = true;
      this.message = "firstname reqd";
      break;
   }
}

Solution 5 - C#

During testing I found that foreach loop after break go to the loop beging and not out of the loop. So I changed foreach into for and break in this case work correctly- after break program flow goes out of the loop.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondotnetLearnView Question on Stackoverflow
Solution 1 - C#configuratorView Answer on Stackoverflow
Solution 2 - C#Greg BeechView Answer on Stackoverflow
Solution 3 - C#SamuelView Answer on Stackoverflow
Solution 4 - C#Marcelo LujanView Answer on Stackoverflow
Solution 5 - C#Sharunas BielskisView Answer on Stackoverflow