Detect when breaking out of loop

.net, c#

Solution

Simple, you already give the answer yourself:

boolean error_with_loop = false;
foreach (var splitAgeOfChild in splitNumberOfChildren) {
      splitChildrensAge           = splitAgeOfChild;
      checkAgeOfChildren          = RemoveInvalidInput.IntIsValid(splitChildrensAge);
      if (checkAgeOfChildren == -1)
      {
           error_with_loop = true;
           problem = "problem with age, stop checking";
           break;
      }
}

if (error_with_loop) {
    ViewBag.Message = problem;
}

Or you throw an `Exception`:

try {
    foreach (var splitAgeOfChild in splitNumberOfChildren) {
          splitChildrensAge           = splitAgeOfChild;
          checkAgeOfChildren          = RemoveInvalidInput.IntIsValid(splitChildrensAge);
          if (checkAgeOfChildren == -1)
          {
                // note: no need to break
                throw new ErrorWithLoopException();
          }
    }
} catch (ErrorWithLoopException e) {
    ViewBag.Message = problem;
}

In fact, you seem to use some kind of integer validation. The `Int32` class has that covered with exceptions: http://msdn.microsoft.com/en-us/library/system.int32.parse%28v=vs.71%29.aspx Your code will actually be shorter (don't know if it is applicable, as I do not know what your validation code does extra):

try {
    foreach (var splitAgeOfChild in splitNumberOfChildren) {
          splitChildrensAge           = splitAgeOfChild;
          checkAgeOfChildren          = Int32.Parse(splitChildrensAge);
    }
} catch (FormatException e) {
    ViewBag.Message = problem;
}

Problem

Can anyone please help as I have run into a wall here, how can I detect when I break out of a loop due to invalid value. For example, if someone enters the ages 3 5 6 7 9 for children that will be ok, if the enter o 3 5 6 7 this will return -1 in my code and exit the loop. How do I detect that and return message ``` public static int IntIsValid(string p) { int pn; bool isNum = int.TryParse(p, out pn); int pnIsvalid = isNum ? pn : -1; return pnIsvalid; } string addDash = Regex.Replace(agesOfChildren, " ", "_"); string[] splitNumberOfChildren = addDash.Split('_'); string splitChildrensAge = string.Empty; int checkAgeOfChildren = 0; string problem = string.Empty; foreach (var splitAgeOfChild in splitNumberOfChildren) { splitChildrensAge = splitAgeOfChild; checkAgeOfChildren = RemoveInvalidInput.IntIsValid(splitChildrensAge); if (checkAgeOfChildren == -1) { problem = "problem with age, stop checking"; break; } } ``` So I would want to do soemthing like ``` if(error with loop == true) { ViewBag.Message = problem; } ``` Hopefully someone can help, as I have gone blank George

Original source