Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Case True

Tags:

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 in use (VB.NET) ?

like image 941
Otávio Décio Avatar asked Apr 27 '09 15:04

Otávio Décio


People also ask

What is select case?

A Select Case statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each select case.

What is Select Case statement in VBA?

The Select Case VBA statement compares an expression with multiple Case statements containing conditions. If a match is found in any of the Case statements, the condition is said to be true. Further, if a condition is true, its corresponding code is executed and no more Case statements are tested.

In what situation you will use Select Case statement?

Select Case is useful when you have three or more conditions that you want to check. You can also use this with two conditions (but I feel If Then Else is easier to use in those cases).


2 Answers

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.

like image 82
Chad Birch Avatar answered Oct 02 '22 12:10

Chad Birch


I'm not sure how this construct offers any advantages over the following:

If testVariable < 0 Then
     Console.Write("You must supply a positive value.")
ElseIf testVariable > 10 Then
     Console.Write("Please enter a number less than 10.")
Else
     Call DoWork(testVariable)
End If

The above structure is short-circuiting, and I don't have to try to work out what it does as it's a standard construct.

like image 44
Patrick McDonald Avatar answered Oct 02 '22 12:10

Patrick McDonald