Conditional Statements
Conditional statements are part of program flow statements that provides the software developer build a complex logical structure within codes. Conditional statements evaluates a condition and produces a true or a false boolean value in order to control the flow of code.
The first conditional statement for every developer to remember first will be the "If ... Then ... Else". Another conditional statement is the "Switch" statement in C# or its equivalent "SELECT CASE" in VB.Net
Let's make a few samples with the conditional statements in order to review the usage of these statements.
If ... Then ... Else
If...Then...Else statement executes a group of code according to the boolean value of an expression in the condition statement. The condition statement is evaluated for a boolean value which is True or False, and if condition generates a True value then the first block of code is run. If there is an ELSE part of the If...Then...Else block then the second block of code is executed for a False generated value of condition.
If you look at the syntax of the If...Then...Else conditional statement, it will be more clear to understand the flow of the code
If if_condition Then
statements
[ ElseIf elseif_condition Then
elseif_statements ]
[ Else
else_statements ]
End If
For example, assume that we design a form where users can enter input values for two integer variables and compare their values.
In the Click event of the button, we can run a similar code block for evaluating the input values
You can also run a single line mode of the If...Then...Else statement. (Note that the If statement is in single line but may be displayed in multi lines on this article because of screen width issues)
Select...Case
Select...Case statement is very useful if you have a list of possible values. The Select...Case statement evaluates an expression and then compares the results of the expression with possible result lists. Then it runs codes depending to which possible result matches the condition.
Select Case testexpression
Case expressionlist
statements
[ Case Else
elsestatements ]
End Select
Let's re-write our sample code using the Select...Case statement
A good thing about the Select...Case is that you can compare a range of values or a list of values in one Case expressionlist
You can apply the range of list values for string values also. For string comparison alphabetical comparison is done to set whether a string value is between the upper and lower limits of the range.