I have a couple IF statements and am trying to figure out how to have the first If statement execute something and not the second but if the first is not true then execute the second one.
if (condition)
{
do_something;
}
if(condition_2)
{
do_something_also;
}
I want the first if statement to happen but after it executes I want it to skip the second if statement.
If the first do_something happens I want to skip the second if statement completely.
How do I go about doing this?
Use else if:
if (condition)
{
do_something;
}
else if(condition_2)
{
do_something_also;
}
Just use if - else if...
if(condition){
do_something();
} else if (condition2){
do_something_also();
}
Related
I have a method that checks multiple conditions to execute further, only to proceed to next if the current condition evaluates to false, otherwise the method will exit without evaluating further conditions. And the number of conditions vary in different implementations (subclasses).
I'm limited by my creativity to make it look any better than using the dreaded goto statement. Is there any better way to do the following:
public bool DoSomething()
{
bool result = true;
if (exclusion1)
{
result = false; goto Exit_Now;
}
if (exclusion2)
{
result = false; goto Exit_Now;
}
if (exclusion3)
{
result = false; goto Exit_Now;
}
if (exclusion4)
{
result = false; goto Exit_Now;
}
if (exclusion5)
{
result = false; goto Exit_Now;
}
if (result)
{
//do something
}
Exit_Now:
return result;
}
EDIT: In response to the answers, I understand using "else if" and conditional OR '||' operator are the obvious choices:
Subquery: which is more performant? I ask because this happens inside a loop and each evaluation takes about 30-40 ms. What is supposed to be finished in under a minute is taking up to two minutes without the goto statements in the code given above. Hence, the query. Thanks for all the help.
If you can fit your exclusion tests into the if statement, just use else if statements;
if (exclusion1)
{
result = false;
}
else if (exclusion2)
// etc ...
else if (result)
{
//do something
}
But I find it's much simpler, and easier to read, to just return early;
if (exclusion1)
return false;
One way to simplify this is to treat the exclusions as a guard clause:
public bool DoSomething()
{
if (exclusion1 ||
exclusion2 ||
exclusion3 ||
exclusion4 ||
exclusion5)
{
return false;
}
//do something
return true;
}
This also has the benefit of removing the nesting of the //do something towards the end.
you can always do this:
result = !(exclusion || exclustion2 ...|| exclusionN);
I am currently studying the conditional constructions. Correct me if I am wrong but else if and else(if(){}) is the same thing... Example:
a=5;
if(a==6)
{
Console.WriteLine("Variable 'a' is 6");
}
else if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
And
a=5;
if(a==6)
{
Console.WriteLine("Variable 'a' is 6");
}
else
{
if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
}
Are these things the same? And if yes why does else if exist if I can write it the "second way"(the second example that I wrote)?
Yes, these are effectively identical.
The reason the "else if" statement exists is to make cleaner code when there are many conditions to test for. For example:
if (a==b) {
//blah
} else if (a==c) {
//blah
} else if (a==d) {
//blah
} else if (a==e) {
//blah
}
is much cleaner than the nested approach
if (a==b) {
//blah
} else {
if (a==c) {
//blah
} else {
if (a==d) {
//blah
} else {
if (a==e) {
//blah
}
}
}
}
why does else if exist
It doesn't. It's not a keyword or construct on its own. Your two examples are identical except that in the second case you've added some superfluous braces and whitespace into the code.
if and else are both simply followed by a single statement. In your first example the statement following the else is:
if(a==5)
{
Console.WriteLine("Variable 'a' is 5");
}
The second example just wraps that same statement in braces, and adds a new line at the start. The new line is ignored, so it doesn't change the semantics, and as the code is already a single statement, wrapping it in braces doesn't change it in any way.
Strictly speaking, there is no such thing as an else if statement. An "else if" is actually just in essence an else with a single line body that happens to be the start of an entirely separate if statement. You can visualize it like this:
var a = 5;
// This if uses a single line
if (a == 6) DoSomething();
// This else is a single line that is also a single-line if
else if (a == 4) DoAnotherThing();
// This else uses a single line as well, but is referring instead to the second if
else DoSomethingElse();
The above script is identical to the following:
if (a == 6)
{
DoSomething();
}
else
{
if (a == 4)
{
DoAnotherThing();
}
else
{
DoSomethingElse();
}
}
Or even this:
if (a == 6)
DoSomething();
else
if (a == 4)
DoAnotherThing();
else
DoSomethingElse();
The reason that it is written as else if so commonly is because it compliments the logical flow of the code. That, and it just looks so much prettier.
Mostly it makes the code cleaner, easier to read, makes indenting better, particularly if you have any conventions on character length of rows (and if you don't then you've got thirty indents in a big if statement, such a pain to read). It also saves space, a few extra characters and indents across thousands of lines may not be much, but why use it if you don't have to. When the code compiles they will pretty much be the exact same in the DLLs anyways.
This may have been answered somewhere before but I could not figure out a good way to word my search.
foreach(item in list)
if(something)
{
dosomething();
}
if(somethingunrelated)
{
dosomethingunrelated();
}
Besides the obvious of being extremely hard to read, is there any way that either if statement might be skipped?
What I think is expected here is that the foreach will iterate over every item in the list and apply the first if statement. After the foreach is completed the second if will be applied once.
I did not write this and am scouring to find an issue on a legacy system. I don't think this is it, but I seem to remember that you can ONLY skip brackets if everything nested skips the brackets as well (in c#.net). Is that correct?
foreach(item in list)
if(something)
{
dosomething();
}
if(somethingunrelated)
{
dosomethingunrelated();
}
is logically the same as this
foreach(item in list)
{
if(something)
{
dosomething();
}
}
if(somethingunrelated)
{
dosomethingunrelated();
}
don't be fooled by indentation.
I seem to remember that you can ONLY skip brackets if everything nested skips the brackets as well
No - if you omit brackets then only the next single statement will be in the scope. The "single statement" can be a bracketed statement, so in your case
foreach(...)
if <--
{ |
| // will get executed for each item
} <--
if
{
// will get executed after the `foreach` is complete.
}
The Second if statement will execute after the foreach loop has completed.
Resharper is telling me that the 'else' in this code is redundant:
if(a)
{
//Do Something
}
else if(b)
{
//Do Something
}
The else does not seem redundant because the else keeps b from being evaluated if a is true. The extra overhead is small if b is a variable, but b could also be an expression.
Is this correct?
It's redundant if you have a some sort of break, continue, return, or throw statement (or even a goto) inside the first if-block that always causes execution to branch outside the current block:
if(a)
{
return 0;
}
else if(b)
{
return 1;
}
In this case, if the code enters the first block, there's no way it will enter the second block, so it's equivalent to:
if(a)
{
return 0;
}
if(b)
{
return 1;
}
You are right in this case, but this is the reason I think they had it to begin with:
Certain if-else conditions can have their else clause removed. Consider the following method:
public int Sign(double d)
{
if (d > 0.0)
return 1;
else
return -1;
}
In the above, the else statement can be safely removed because its if clause returns from the method. Thus, even without the else, there’s no way you’ll be able to proceed past the if clause body.
It doesn't appear redundant to me. Removing the else would result in different program flow if both a and b are true.
In VB I can write a loop that always executes at least once. For example:
Do
[code]
Loop While [condition]
Is there a way to do that in C#?
Sure:
do
{
...
} while (condition);
See do (C# Reference).
do
{
// code
} while (condition)
Alternatively
bool finished = false ;
while ( !finished )
{
// do something
finished = // evaluate a new foo
}
I've never been a huge fan of do/while
TopOfLoop:
// ...
if (condition)
{
goto TopOfLoop;
}
No career is complete without at least one goto.