Apparently this used to be a way in VB6 and VBA to short circuit and execute the first true case:
Select Case True
End Select
Is this still
Select Case
is a powerful operator by itself. But even though Select Case True
is still supported, it is better to be avoided for maintainability perspective. You always have to justify the need. If needed badly, you can even use DoEvents
and GoTo
. For the accepted answer, it could have been written like this instead:
Select Case testVariable
Case Is < 0 : Console.Write("You must supply a non-negative value.")
Case Is > 10 : Console.Write("Please enter a number from 0-10.")
Case Else : Call DoWork(testVariable)
End Select
Another reason for using the construct SELECT CASE TRUE is when your case statements evaluate to a boolean value. The SELECT CASE needs to have all cases evaluate to the same data type as the control. If you are looking at a string data type, then all of the case statements need to be strings as well.
SELECT CASE [string]
CASE "String 1", "String 2"
[do a thing]
CASE "String 3"
[do another thing]
END SELECT
However if you are comparing partial strings using the LIKE operator then your case data type becomes boolean which will not match the string control. The following code will not work:
SELECT CASE [string]
CASE LIKE "*1", "*2"
[do a thing]
CASE LIKE "*3"
[do another thing]
END SELECT
In order to use wildcards (and thus have boolean case outcomes) you have to have a boolean control value, thus the structure needs to be:
SELECT CASE TRUE
CASE [string] LIKE "*1", "*2"
[do a thing]
CASE [string] LIKE "*3"
[do another thing]
END SELECT
I suppose you could use IF...ELSEIF
IF [string] LIKE "*1" AND [string] LIKE "*2" THEN
[do a thing]
ELSEIF [string] LIKE "*3"
[do another thing]
END IF
Personally I find the SELECT CASE is easier to use and read when there are more than three options. I use IF...ELSE and IF...ELSEIF when I have to evaluate two or three different options (>, =, <) or if I am testing a value for a specific range of 'valid' entries. If instead the entry has more variety and I need to determine which of ten possibilities has happened the SELECT CASE is a much easier construct to use as it eliminates the need for multiple OR statements.
This syntax is often used instead of an If...ElseIf
statement. Some people find it a little easier to read. For example:
Select Case True
Case testVariable < 0
Console.Write("You must supply a positive value.")
Case testVariable > 10
Console.Write("Please enter a number from 0-10.")
Case True
Call DoWork(testVariable)
End Select
The answer is that yes, this still works in VB.NET. Just take care with when you use it, because it's not a "standard programming construct" and may be unfamiliar to people that have to maintain your code in the future.