Imagine a condintion should be true for a method to do its stuff. Which block represents the best approach (performance related and readability), or if not what is your suggestion?!
private void method()
{
if(!condition)
{
MessageBox.Show("ERROR!");
return;
}
else
{
//DO STUFF
}
}
OR
private void method()
{
if(condition)
{
//DO STUFF
}
else
{
MessageBox.Show("ERROR!");
return;
}
}
Well, neither, as you wouldn’t use both
elseandreturn.So, you would either do:
or:
or:
or:
Which you use depends mostly on what the code actually does. The code is seldom as simple as in the examples, so it matters what more the code will do.
The first two have the advantage of having a single exit point, which often makes it easier to follow the code. You would usually put the shorter code first, as it’s easier to spot there than in an
elseafter a larger code block.The third is often used to validate input before continuing with the main code, and you can easily have more than one validation:
The fourth is useful if you have several conditions that you don’t want to put in the same
ifstatement: