VB.NET 1.1 Tutorial - Conditional If...Then...Else StatementThe conditional statement If, selects one of a number of possible statements for execution based on the value of a boolean expression. The If statement comes in one of two forms If conditional-test Then statement or If conditional-test Then multiline-statements End If or If conditional-test Then true-statements Else false-statements End If Where the conditional-test evaluates to True or False and the statements are blocks of code to be executed. This is best shown in a simple example: Dim Number As Integer Number = 53 ' Initialize variable If Number >= 0 Then Console.WriteLine( "Number is positive" ) Else Console.WriteLine( "Number is negative" ) End If So what does this mean? Simply put, it means that if the Integer in the variable Number is greater than or equal to zero, then the application will write the line "Number is positive" to the console. Otherwise the application will write the line "Number is negative" to the console. Although the output is not technically correct, it shows how to use an If statement. We can fix this allowing us to show nested If statements. Dim Number As Integer
Number = 53 ' Initialize variable
If Number >= 0 Then
If Number > 0 Then
Console.WriteLine( "Number is positive" )
Else
Console.WriteLine( "Number is zero" )
End If
Else
Console.WriteLine( "Number is negative" )
End If
Alternatively, this can also be written using the Else If statement: Dim Number As Integer Number = 53 ' Initialize variable If Number = 0 Then Console.WriteLine( "Number is zero" ) Else If Number > 0 Then Console.WriteLine( "Number is positive" ) Else Console.WriteLine( "Number is negative" ) End If Shorthand NotationBe wary of using single line If statements. It is easy to get confused as to what the code is really doing. Here is an example: If A > 10 Then A = A + 1 : B = B + A : C = C + B It is not hard to see what order this code will be evaluated in, the above code is equivalent to: If A > 10 Then A = A + 1 B = B + A C = C + B End If By use of the a colon (:), we can almalgamate more than one line of code into one line of code. ReferencesFor more information on If...Then...Else Statements, visit MSDN at microsoft here. What Next?Return to the Tutorial Contents. |