I know this may seem a bit like nitpicking, but would it make any difference to use

public int foo()
        {
            if (myInt == 1) return 2;
            if (myInt == 2) return 1;
            return 0;
        }

or

public int bar()
        {
            if (myInt == 1) return 2;
            else if (myInt == 2) return 1;
            else return 0;
        }

Or perhaps tehre are other solutions?
I know also you probably can dig this out examining IL dissasembly, but I'm a layman on this subject.

Recommended Answers

All 5 Replies

The second example

@Slavi: Thanks for your answer :) , but could you elaborate a bit more on the why?
I also have the impression this is the better choice, but just wondering why.

The two examples are functionally identical. Which one you'd use depends on which fits better with the rest of the code.

In the second example it will skip the rest of the else if statements when it has found a satisfying condition. In your first example every if statement will be evaluated. In your short example it doesn't make much difference. The difference is noticed in a loop with many iterations or if you have many if statements or if your if statements must perform more complex (time consuming) evaluations. Of course this all depends on the frequency of a satisfying condition being found. The greatest benefit will result in the second example if you order the statements from most likely to occur to least likely to occur.

commented: Great answer! +15

2nd example.

Now in your case it's rather simple here, but if you use two 'ifs' like that you are going to have to run the code on each, and risk them both performing a task instead of one.

Plus if another developer were to work on your code, the 2nd example paints a better picture of the logic

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.