Answered If vs if, if else

LupusRex

Member
Joined
Oct 30, 2019
Messages
16
Programming Experience
Beginner
Hi
As I already have said before I'm all new to C#, so sorry if this is a noob question.

Is there any special reason/performance improvement by using "if, if else" over "if, if, if."?

Like this:
C#:
if (a) {
    // Do something.
}
else if (b) {
    // Do something else
}
else if (c){
    // :)
}

// Only if statements

if (a) {
    // Do something.
}
if (b) {
    // Do something else
}
if (c){
    // :)
}

My reason for asking this is, that I have a lot of validations to make, where I use if statements due to the lack of select statements in C# (I know that select and if doe's the same, but I find that select statements is more readable, that a lot of if statements), and a switch statement don't work in this case.

Ohh, and what is the different between using {} and not in if statements (I've seen both types, when I search for coding answers).

Cheers
/LR
 
The curly braces are only needed if you have multiple statements for // Do something. If there is only one statement, then technically you don't need them. You'll find that when you were with a team (or an open source project) many of them will have a style guide, and most style guides will stipulate that you use the curly braces regardless of there being only one statement or multiple statements. The usual justification for this stylistic rule is that it is a very good preventative action to make sure of the intent of the person adding code.

Here's an example:
Before:
C#:
if (some condition)
    do something based on condition;
do always;
After:
C#:
if (some condition)
    do something based on condition;
    do another thing;    // <-- new code added
do always;
The do another thing; will always be executed because the compiler sees:
C#:
if (some condition)
    do something based on condition;
do another thing;
do always;
So if curly braces were used, there's a better chance of the right thing being done by the next person adding code.
Before:
C#:
if (some condition)
{
    do something based on condition;
}
do always;
After (intent was the other thing is based on the condition):
C#:
if (some condition)
{
    do something based on condition;
    do another thing;    // <-- new code added
}
do always;
 
Is there any special reason/performance improvement by using "if, if else" over "if, if, if."?
You are prematurely optimizing. As Knuth says: "Premature optimization is the root of all evil."

In general, C# compiler will convert a switch series of if-else if statements. Occasionally, the compiler will optimize the switch statement into using a Dictionary, much like the way a C or C++ compiler may decide to compile the code to use a jump table. You shouldn't worry about this though unless you run a profiler and narrow down the reason for the slowness of your code being the choice of using a switch or a series of if-else if statements.

Your primary job as a programmer is to communicate. You want to make your code easy to understand for the next person to look at your code -- which could very well be yourself in a few years after you've set the code aside for a while.
“Programs must be written for people to read, and only incidentally for machines to execute.”

― Harold Abelson, Structure and Interpretation of Computer Programs
 
Hi Skydiver
Ahh that makes sens, I always use the {} corse I somewhere read that it was what I should do, though I often find that I can't use vars from inside the {} outside :(

like.
C#:
if (a){
    var myVar = "Test";
}
else{
    var myVar = "Other"
}
Console.WriteLine(myVar);
If I don't use the {} could I then use the vars from within the statements?

:) It was more thought as should I use if, else if, else if instead of if, if, if (rules of coding, or some thing like that).

Yes, thats why I use comments, and comments on the comments in my code :D

Cheers
/LR
 
There is a difference between the following:
C#:
if (a) {
    // do A
}
else if (b) {
    // do B
}
else if (c) {
    // do C
}
and
C#:
if (a) {
    // do A
}
if (b) {
    // do B
}
if (c) {
    // do C
}

The latter will always test conditions a, b, and c.

The former will only test b if a is false; and test c if b is false. This is yet another case of not putting braces around single statements. If braces were put in place, and the correct indents were applied, the first code would look like:
C#:
if (a) {
    // do A
}
else {
    if (b) {
        // do B
    }
    else {
        if (c) {
            // do C
        }
    }
}
 
Ohh of corse that gives it self, now that you explains it.. Doo I should had thought of that my self ?.

Scoping rules? So everything in {} only exists there and can't be used outside? What if I don't use the {} could I then use my vars outside the if statement?

Cheers
/LR
 
Are you sure it works for you? It doesn't for me:
C#:
if (true)
    var x = 12;      // !!! CS1023 Embedded statement cannot be a declaration or labeled statement
else
    var y = 16;      // !!! CS1023 Embedded statement cannot be a declaration or labeled statement
Console.WriteLine(x);      // !!! CS0103 The name 'x' does not exist in the current context
 
RE: My post #3 above.
I forgot to add:
So the point of the communication quote there is that sometimes it is better to communicate an idea with a switch statement because it makes it obvious to the reader that there are multiple branches that the code can take. Other times, the if-else if statement makes better sense when you want to tell the reader that there are multiple possibilities, but you want to deal each of the cases in some kind of priority order. Other times, depending on the code you are writing, one or the other is just easier to read.
 
Scoping rules? So everything in {} only exists there and can't be used outside?
No. You are missing the point of what they are and when to use them : { }. Consider the brackets as a way to use a grouping of objects from within the brackets condition.
If you have : if (!b) i++;Console.WriteLine(i); - Everything after the first ; is considered not part of the conditional statement. Meaning, there is nothing to stop the console from writing 10 from this code :
C#:
            bool b = true; int i = 10;
            if (!b) i++;Console.WriteLine(i);
The above line without brackets is the equivalent of how the compiler sees it. And would be like so :
C#:
            if (!b)
            {
                i++;
            }
            Console.WriteLine(i);
Again, only the parts inside the { } will be executed as part of the conditional statement being met, just as we've done here : if (!b) i++;Console.WriteLine(i); I believe it was pointed out that you don't need to use brackets if your condition provides only one action as part of that condition. But if you wanted to execute more than one action for your conditional statement, then you will need to use the : { } brackets to group those actions and make them part of the conditional statement.
 
@Skydiver
I haven't tried, it was a question if one could do it that way, but that you answered with your code :)
And now when I think about it, it wasn't in a if statement but in a using statement I failed to "reuse" my var outside the {}, but I guess that it's same rule there :)
I do use switch where I can, but in this case I have multiply vars that I need to handle, and therefor I can't use a switch statement.

@Sheepings
So regardless if I use {} or not, the compiler would still handle the code as if the were there.

Cheers
/LR
 
Ups missed that last part :$
thx :)

Cheers
/LR
 
Back
Top Bottom