0

I'm trying to break a forloop using break as traditional, but in this case I find myself stuck with this nested switch where the break only works into the switch scope and the loop keeps iterating.

for (int i = 0; i < lenght; i++)
{
    switch (enum)
    {
        case Enum.some_1: break;

        case Enum.some_2: break;

        case Enum.some_3: break; 
    }
}
3
  • It would be so much easier to provide a better solution to your issue if you would provide a reasonable problem statement. With the sample you provided it makes no sense to have a for loop because you are not even using he index "i" in any way. You appear to be iterating over an array or list, but you have not provided enough information. Commented Mar 28, 2020 at 1:22
  • @Barns you're right, I forgot to use the "i" index in the example but I use it for sure. Commented Mar 28, 2020 at 15:06
  • My point is: there could be alternate solutions to this "problem" that would better fit your code, but it is impossible to know this, because it doesn't look like you have provided enough detail minimal reproducible example. Considering you have not yet accepted any of the viable solution below, it would appear you are not satisfied with the provided options. Commented Mar 28, 2020 at 15:44

3 Answers 3

2

There are multiple options to approach this:

Using helper variable

bool exit = false;
for (int i = 0; i < length && !exit; i++)
{
  switch(enum)
  {
    case Enum.case_which_breaks:
      exit = true;
      break;

    // other cases
  }

  // some other code, which may use `i`
}

Using helper method

This would be simpler, if you could refactor out the whole for block into a helper method. In this case, you'll use return rather than break.

private Result HandleInternally(int length, Enum enum, Request params)
{
  for (int i = 0; i < length; i++)
  switch (enum)
  {
    case Enum.case_which_breaks:
      Result result = new Result(); //populate the result
      return result;
    // other cases
  }


}

And then in the consuming code simply call the method.

Sign up to request clarification or add additional context in comments.

1 Comment

The helper method. Much cleaner.
1
bool exitForLoop = false;
for (int i = 0; i < length && !exitForLoop; i++)
{
    switch (enum)
    {
        case Enum.some_1: exitForLoop = true; break;
        case Enum.some_2: break;
        case Enum.some_3: break; 
    }
}

Comments

1
    bool exit = false;
    int i = 0;
    while (!exit && i < length)
    {
        switch (enum)
        {
        case Enum.some_1: exit = true; break;

        case Enum.some_2: exit = true; break;

        case Enum.some_3: exit = true; break; 
        }
        i++;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.