Lobsang White
Lobsang White

Reputation: 107

Break for loop statement with nested switch

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

Upvotes: 0

Views: 645

Answers (3)

Kim
Kim

Reputation: 181

    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++;
    }

Upvotes: 1

Artak
Artak

Reputation: 2887

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.

Upvotes: 2

Zer0
Zer0

Reputation: 7354

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

Upvotes: 1

Related Questions