Go and execute else statement from if statement C#

Viewed 133

Below are the if-else conditions statements I am using. I was thinking to remove code duplication inside //Statements 2

if (true)
{
    List<string> usersList=getUsersList();
    if(usersList.Length > 0){   
    //Statements 1
    ..............
    }
    else{
    //Statements 2
    .............
    }
}
else
{
    //Statements 2
    .............
}

In the above code Need to repeat Statements 2. Is there way to send execution to main else loop.

2 Answers

Maybe something like this?

bool runSecondBlock = !firstCondition;
if (firstCondition)
{
  List<string> usersList=getUsersList();
  if(usersList.Length > 0){   
    //Statements 1
    ..............
  }
  else {
    runSecondBlock = true;
  }
}
if (runSecondBlock)
{
    //Statements 2
    .............
}

You can use conditional logical operator && to accomplish this, but take care, if your decision tree becomes more complicated, it can get messy rather quickly.

if (condition1 && condition2) //both need to be "true" to execute statements 1
{
   //Statements 1
}

else
{
   //Statements 2
}
Related