Visual Basic .NET/Branch statements
From Wikibooks, the open-content textbooks collection
A branch statement, or conditional statement, is code that allows you to test whether statements are true or false and then execute some code based on these comparisons.
Contents |
[edit] The Branch Statements
- If/ElseIf/Else
- Select Case
[edit] The Branch Statements Explained
[edit] If...ElseIf...Else Statement
If/Else statements are used to conditionally execute code based on condition provided. If the condition provided in the If statement evaluates to true, the code in the block is executed. Otherwise, execution would proceed to the optional ElseIf statements, or the Else statement. ElseIf and Else are not required parts of an If statement.
An example of the If/ElseIf/Else branch statement is:
'The following variable declarations are for the following example only. They are not needed in real life.
Dim x As Integer Dim y As Integer If x = y Then 'Whatever will happen if x = y ElseIf x < y Then 'Whatever will happen if x < y Else 'Whatever will happen if x isn't = to y and x isn't < to y End If
[edit] Select Case Statement
Either strings or numbers can be used for a Select Case statement.
Select Case statements are usually used to avoid long chains of If/ElseIf/.../ElseIf/Else statements.
An example of a Select
Dim nCPU as Integer
Select Case nCPU
Case 0
'No CPU!
Case 1
'Single CPU
Case 2
'Dual CPU machine
Case 4
'Quad CPU machine
Case 3, 5 To 8
'3, 5, 6, 7, 8 CPU's
Case Else
'Something more than 8
End Select
[edit] Boolean Operators
Boolean operators in Visual Basic .NET now accommodate for short circuit boolean evaluation, most other languages always apply short circuit boolean evaluation by default (usually, this can be turned off with a compiler option), consider the following boolean statement:
functionA() and functionB()
With this statement, when short-circuit boolean evaluation is used, the second function will only be called if the first function returns true, this is because if functionA returns false it becomes irrelevant to the outcome of the statement whether functionB returns true or not.
However, when no short-circuit boolean evaluation is used, both of the functions will be called irrespective of whether the first part of the statement returns true or false.
Something to note with short-circuit boolean evaluation is that the order of the parameters can become important when it is used.
Due to previous versions of Visual Basic not having short circuit boolean evaluation, Microsoft has decided to preserve backward compatibility and add two new boolean logic identifiers which support short-circuit boolean evaluation, so in addition to the standard boolean operators:
Not And Or Xor
There are also two new operators which function using short-circuit boolean evaluation, and they are:
AndAlso OrElse