What is the difference between if and else if in C#? For example if i write
if (x==5){
do something
}
And
else if (x==5){
do something
}
Are they totally same… so ? What is the difference?
**IF** you are confused
read the c# spec
**ELSE IF** you are kind of confused
read some books
**ELSE**
everything should be OK.
Courtesy: https://stackoverflow.com/a/1445365/5352399
Jokes are apart, usually an if statement follows this sort of structure:
if (condition)
{
// executed only if "condition" is true
}
else if (other condition)
{
// executed only if "condition" was false and "other condition" is true
}
else
{
// executed only if both "condition" and "other condition" were false
}
The if portion is the only block that is absolutely mandatory. else if allows you to say "ok, if the previous condition was not true, then if this condition is true...". The else says "if none of the conditions above were true..."
You can have multiple else if blocks, but only one if block and only one (or zero) else blocks.
Answer reference: https://stackoverflow.com/a/1439915/5352399
Please read about C# control statements that will give you comprehensive idea.
They aren't the same.
if (true)
DoSomething();
if (true)
DoSomething();
Versus
if (true)
DoSomething();
else if (true)
DoSomething();
The first example does something twice; the second does something only once.
Use else when you don't want multiple cases to be hit.
This is a little tricky, if you use plugins like resharper and you try to write a if sentence preceding of else if sentences, resharper will tell you that the 'else' in 'else if' sentence is redundant and will refactor your code to only if sentences.
Performance issue? or we really don't know how is working c# at this days?
Related
I want to check if the result from a request is having any issue. I categorize it into two: i) server error, ii) something else that is not a success. The third category is, result actually being a success. However, in the third category, I don't want to do anything.
So, my desirable code is:
if res.status().is_server_error() {
panic!("server error!");
} else if !(res.status.is_success()){
panic!("Something else happened. Status: {:?}", res.status());
} else{
pass;
}
I am aware of other ways to achieve this result: using match, ifs instead of if else if. But I wanted to learn what is the corresponding keyword of pass, like we have in Python. My aim is: if result is successful, just move along, if not, there are two ways to handle that panic.
Behold!
if predicate {
do_things();
} else {
// pass
}
Or even better
if predicate {
do_things();
} // pass
Or as I’ve recently taken to calling it the implicit + pass system
if predicate {
do_things();
}
In all seriousness there is no pass and no need for a pass in rust. As for why it exists in python, check out this answer
Python needs pass because it uses indentation-based blocks, so it requires some syntax to "do nothing". For example, this would be a syntax error in a Python program:
# syntax error - function definition cannot be empty
def ignore(_doc):
# do nothing
count = process_docs(docs, ignore) # just count the docs
The ignore function has to contain a block, which in turn must contain at least one statement. We could insert a dummy statement like None, but Python provides pass which compiles to nothing and signals the intention (to do nothing) to the human reader.
This is not needed in Rust because Rust uses braces for blocks, so one can always create an empty block simply using {}:
// no error - empty blocks are fine
fn ignore(_doc: &Document) {
// do nothing
}
let count = process_docs(docs, ignore); // just count the docs
Of course, in both idiomatic Python and Rust, one would use a closure for something as simple as the above ignore function, but there are still situations where pass and empty blocks are genuinely useful.
I'd like to combine an mce_loop with threads created by threads->create, but fail. The simplified script below never reaches the second print line. Why?
(It works if I create the threads first, but in my real script this would make other parts more complicated).
use MCE::Loop;
mce_loop { } (0);
print "OK\n";
threads->create (sub {});
print "never reached ..\n";
With the help of the (later deleted) example posted by Håkon Hægland I figured out what really helps in my simplified example. I still don't get the reason for this strange behaviour.
use MCE::Loop;
mce_loop { } (0);
MCE->new ()->run; # this, but why?
print "OK\n";
threads->create (sub {});
print "never reached ..\n";
I just noticed that Spock does not assert the conditions if I add an if clause in the expect block as in
def myTest() {
given:
a = true
expect:
if ( a ) {
1 == 2
}
else {
1 == 1
}
}
The above test will pass since the conditions are not checked. Or the condition checking does not get forwarded pass the if statement.
The workaround to this is to add assert statements inside the if block, i.e. assert 1 == 2.
What I'm interested is, is why the functionality is like this? Is there some other way to workaround this? I'm assuming this has something to do with Groovy if statement functionality, but I don't know the language details well enough. Most probably the if statement does not return anything for the Spock's expect block to work with.
This has nothing to do with groovy. Spock's documentation clearly states that only top-level expressions are considered in then and expect as conditions. It is by design.
Search the link for top.
Wondering if I can break out of my case if the break is in an if statement, or if the break will just exit the if and not the case. I only want to fallthrough to the next case if the else is executed. Thanks
case PS_STARTED:
readyForPwrDn_b = appReadyForPwrDn_b;
if (!readyForPwrDn_b)
{
break;
}
else
{
CurrentPowerState_e = PS_COMPLETE;
}
//fallthrough
case PS_COMPLETE:
There's no such thing as breaking out of an if. break applies only to switch and to loops in all the programming languages I'm familiar with.
PHP:
break ends execution of the current for, foreach, while, do-while or switch structure.
Javascript:
The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
C++:
The break statement is used with the conditional switch statement and with the do, for, and while loop statements.
However, these all apply to non-labeled break statements. In some languages you can write:
myIf:
if (!readyForPwrDn_b) {
break myIf;
} else {
CurrentPowerState_e = PS_COMPLETE;
}
This would just break out of the if.
if (condition)
{
//Do your thing
if (breakOutCondition)
return;
//Continue your code
}
This if statement would work, but there is an easy, clean way of getting out of a loop like this. You could use a goto to break this variable scope and it will make it loop a hell of alot cleaner. WARNING: goto is sometimes dreaded because it is essentially a break in disguise.
if (breakoutcondition)
{
...
goto foo;
...
}
foo:
//Continue here
Which one is good to use when there is a large number of branching flow in Node.JS Program.
switch
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
OR
if-else
if (condition1)
{
execute code block 1
}
else if(condition2)
{
execute code block 2
}
else
{
code to be executed if n is different from condition1 and condition2
}
For just a few items, the difference is small. If you have many items you should definitely use a switch. It give better performance than if-else.
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if-else where the last item takes much more time to reach as it has to evaluate every previous condition first..
switch(n)
{
case 1,3,4:
execute code block 1
break;
case 2,5,9,10:
execute code block 2
break;
default:
code to be executed if n is different from first 2 cases.
}
To write down the if...else if...else steps for the above case, you will have to write the 'OR (||)' condition-statement and repeat the variable 'n' in the statement, Where as switch cases can be separated by just a comma ','. Thus switch is more readable for such a case.