Question:
Visual Basic programming... When to use "If/Else" Statement or "Select Case" Statement?
anonymous
2008-12-30 00:56:24 UTC
I've used both If/ElseIf/Else Statements, and Select Case Statements.

Basically the same thing. But, I don't know how to explain it, but in some situations different statements just seem to "flow" better.

So, I guess my question is, is there a right or wrong time to use one of these two statements? Are there Pros/Cons?
Five answers:
Scott B
2008-12-30 08:06:55 UTC
If you are testing a single variable for two or more expressions or ranges, select/case may be best.



If you're testing more than one variable or you are testing for only a single expression, an if/else is needed



For example,



Dim number As Integer

...

Select Case number

Case 1 To 4, 7 To 9, 11, 13, Is > maxNumber

...



Since you are testing only one variable (number) and it has several possible expressions, a select/case is a good choice. Of course, when you need to do different things depending on the value of number, another case is needed.



I doubt that performance is an issue because the same type of code should be generated for if/else and case.
linaris
2016-11-02 16:39:30 UTC
Visual Basic Switch Statement
braggcolin
2008-12-30 01:07:47 UTC
You're right they are esentially the same but with some subtle differences.



As a general rule you would use the select statement when you have 1 condition to test but with several outcomes rather than having lots of ugly elseif statements asking for the same info



ElseIf statements should be used when the test conditions are different.



In fact by using the select statement correctly you are speeding up the performance of you applications because conditions are only tested once at the top of the statement block



A good example of a select statement could be an order processing system. You ask the user for their debit or credit card type at the top of the select statement and then you process each card type differently underneath.
Chie
2008-12-30 06:11:04 UTC
If there's a variable or expression that you want to test the value for special cases, you would probably use the Select Case statements. Otherwise, If...Then...Else statements would be okay.
sharad k
2008-12-30 01:06:55 UTC
see both can be used .but use switch case as it is clean incase of if else you can give sub conditions also .but you need to keep track of matching else as the else part goes to nearest if....


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...