How to break out of an IF statement
I have code like this:
public void Method()
{
if(something)
{
// Some code
if(something2)
{
// Now I should break from ifs and go to the code outside ifs
}
return;
}
// The code I want to go if the second if is true
}
Is there a possibility to go to that code after ifs without using any go to statement or extracting rest of the code to the other method?
Yes, I know Else ;)
But this code is farly long and should be run IF the first IF is false and when the first IF is true and the second is false.
So extracting a method I think is the best idea.
Solution 1:
To answer your question:
public void Method()
{
do
{
if (something)
{
// some code
if (something2)
{
break;
}
return;
}
break;
}
while( false );
// The code I want to go if the second `if` is true
}
Solution 2:
You can use a goto to drop past some code. In the example, if thing1 is true then the check for things2 is bypassed.
if (something) {
do_stuff();
if (thing1) {
do_thing1();
goto SkipToEnd;
}
if (thing2) {
do_thing2();
}
SkipToEnd:
do_thing3();
}
Solution 3:
This is a variation of something I learned several years back. Apparently, this is popular with C++ developers.
First off, I think I know why you want to break out of IF blocks. For me, I don't like a bunch of nested blocks because 1) it makes the code look messy and 2) it can be a PITA to maintain if you have to move logic around.
Consider a do/while
loop instead:
public void Method()
{
bool something = true, something2 = false;
do
{
if (!something)
break;
if (something2)
break;
} while (false);
}
The do/while
loop is guaranteed to run only once just like an IF block thanks to the hardcoded false
condition. When you want to exit early, just break
.
Solution 4:
public void Method()
{
if(something)
{
// Some code
if(something2)
{
// Now I should break from ifs and go to the code outside ifs
goto done;
}
return;
}
// The code I want to go if the second if is true
done: // etc.
}
Same question
Long answer
Solution 5:
Another way starting from C# 7.0 would be using local functions. You could name the local function with a meaningful name, and call it directly before declaring it (for clarity). Here is your example rewritten:
public void Method()
{
// Some code here
bool something = true, something2 = true;
DoSomething();
void DoSomething()
{
if (something)
{
// Some code
if (something2)
{
// Now I should break from ifs and go to the code outside ifs
return;
}
return;
}
}
// The code I want to go if the second if is true
// More code here
}