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; 
    }
}
Lobsang White
  • 97
  • 1
  • 1
  • 14
  • 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. – Barns Mar 28 '20 at 01:22
  • @Barns you're right, I forgot to use the "i" index in the example but I use it for sure. – Lobsang White Mar 28 '20 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 [mcve]. Considering you have not yet accepted any of the viable solution below, it would appear you are not satisfied with the provided options. – Barns Mar 28 '20 at 15:44

3 Answers3

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.

Artak
  • 2,819
  • 20
  • 31
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; 
    }
}
Zer0
  • 7,191
  • 1
  • 20
  • 34
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++;
    }
Kim
  • 136
  • 7