If... Else or Case? when use one or the other

  • Thread starter Thread starter AA
  • Start date Start date
A

AA

Somebody know when is recommended to use If Else condition and when is
recommended to use Case?

Thanks a lot

AA
 
I would say that the other way around.

Use an If Then statement when 2 or more explicit conditions need to be
tested and use a Case when just one condition needs to be tested.

Consider this:

If x="foo" then
do something
ElseIf x="foofoo" then
do something else
ElseIf x="foofoofoo" then
do something else
End If

In this example (although perfectly legitimate code), the value of x must be
determined 3 times.
Now, look at the same code in a Case statement:

Select Case x
Case "foo"
do something
Case "foofoo"
do something else
Case "foofoofoo"
do something else
End Select

Here, the value of x only needs to be determined one time. Notice that with
the Case statement, you only look at one condition throughout the Case, but
with the If...Then statement you can make new tests that check the
previously used variable for a new value or some new conditon completely.

David Williams said:
My suggestion is to use a Select... Case when you have more than two
conditions that you are checking or any time that you are checking an enum.
 
So, I could use Case (always) when I have just one expression to evaluate,
no matter how many times? or We can say:

When you have one expresion "x" and two or more condition x=a, x=b

Thanks a lot
 
Sure:

Select Case Case 1
Case 1
do something
Case 1
do something
Case 1
do something
Case 1
do something
 
Sorry that last message got sent before I was done:

Sure:

Select Case x
Case 15
do something
Case 12
do something
Case 11
do something
Case 165
do something
Case Else
default action(s)
End Select
 
Back
Top