How can I go about doing this so if the "if" statement is true, to skip the code below the foreach loop and to go on with the rest of the program
void()
{
foreach()
{
if()
{
}
}
//code I want to skip if "if" statement is true
}
There's no way to directly do what you want (without "goto" labels -- perish the thought!), but you can use the "break" keyword, and set a variable you can refer to later.
void()
{
var testWasTrue = false;
foreach()
{
if()
{
testWasTrue = true;
break; // break out of the "foreach"
}
}
if( !testWasTrue ) {
//code I want to skip if "if" statement is true
}
}
I know this was already answered, but I figured I'd throw in my 2 cents since nobody considered abstracting the check to a separate method:
void()
{
if (ShouldDoStuff(myCollection))
DoStuff(myCollection);
else
DoOtherStuff(myCollection);
}
private bool ShouldDoStuff(collection)
{
foreach()
{
if ()
return true;
}
return false;
}
This provides a much cleaner code at the higher level for dealing with your algorithms and removes all the clutter discussed about. It cleanly separates the tasks in void()
of checking and performing the actions and readers instantly know exactly what the program flow is without having to discern what they're doing with a boolean or break logic lurking about. No single method has more than 1 responsibility or task.
Yeah, it's possible the poster wants to do other work in their foreach, but that's an entirely different discussion and not what was described in their question. If you simply want to check if the given collection (or object) satisfies a certain condition, that check can be moved to a separate method. Even leaves the door open for automated unit tests for all three components.
Even if DoStuff
and DoOtherStuff
are not abstracted to their own methods, it provides nicer readability and logical flow.
void()
{
bool process = true;
foreach()
{
if()
{
process = false;
break;
}
}
if (process)
{
//code I want to skip if "if" statement is true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With