How do I exit a foreach loop in C#?

dotnetLearn picture dotnetLearn · Jan 19, 2009 · Viewed 225k times · Source
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?

Answer

configurator picture configurator · Jan 19, 2009

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);