Home Articles My Account Messages Tools Join
Tech Blog, ASP.Net, VB.Net, C#.Net, Programming Help, Help Guide
StellarPC.com | Replacing nested if statements with Select Case and the To clause (VB.Net)
Replacing nested if statements with Select Case and the To clause (VB.Net)
Written by: Justin Rich

Replacing nested if statements with Select Case and the To clause

Select Case statements can be very useful to programmers and there are versions of this logic in most languages (such as the switch in C variations). In VB.Net, the Select Case can be written like this:

Dim varName as Integer = 2

Select Case varName
Case 1
'Do this condition
Case 2
'Do this
Case 3
'do this
Case Else
'do something else
End Select


This evaluates in such a manner that it looks at the value of the variable and only does the case which it applies to and in this example it would be the "Case 3" because the var value was 3. In this, we can also use a To clause to do ranges of cases. This is where VB.Net seems to be more powerful because there isn't an easy range possibility in the variations of this logic of other languages. In the example above you can do this instead:

Case 1 to 5
'do this
Case 5 to 10
'do this
Case Else
'do else


Knowing this, you're now free from having to nest mutiple if statements to try to check the value of a variable range and save some typing.


p.s. In classic VB or classic ASP, this was Case 5 thru 10 instead of 5 to 10. I think they changed this because thru was confusing as an abbreviated word not normally found in programming.
New Post Next 50 | Previous 50
Post# Subject: Posted By: Time:
New Post Next 50| Previous 50