Home

Introduction to Conditional Statements

 

Checking Whether a Condition is True/False

 

Introduction

In some programming assignments, you must find out whether a given situation bears a valid value. This is done by checking a condition. To support this, the Visual Basic language provides a series of words that can be combined to perform this checking. Checking a condition usually produces a True or a False result. Once the condition has been checked, you can use the result (as True or False) to take action.

 

If a Condition is True/False, Then What?

The If...Then statement examines the truthfulness of an expression. Its formula is:

If ConditionToCheck Then Statement

There are two ways you can use the If...Then statement. If the conditional formula is short enough, you can write it on one line, like this:

If ConditionToCheck Then Statement

Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim IsMarried As Boolean
    Dim TaxRate As Double

    TaxRate = 33.0

    Response.Write("Tax Rate: " & TaxRate & "%")
    Response.Write("<br />")

    IsMarried = True
    If IsMarried = True Then TaxRate = 30.65

    Response.Write("Tax Rate: " & TaxRate & "%")
%>

</body>
</html>

This would produce:

Conditions

If there are many statements to execute as a truthful result of the condition, you should write the statements on alternate lines. Of course, you can use this technique even if the condition you are examining is short. In this case, one very important rule to keep is to terminate the conditional statement with End If. The formula used is:

If ConditionToCheck Then
    Statement
End If

Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim IsMarried As Boolean
        Dim TaxRate As Double

        TaxRate = 33.0

        Response.Write("Tax Rate: " & TaxRate & "%")
    Response.Write("<br />")

        IsMarried = True
        If IsMarried = True Then
            TaxRate = 30.65

            Response.Write("Tax Rate: " & TaxRate & "%")
        End If
%>

</body>
</html>

Using the Default Value of a Boolean Expression

In the previous lesson, we saw that when you declare a Boolean variable, by default, it is initialized with the False value. Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim IsMarried As Boolean

    Response.Write("Employee Is Married? " & IsMarried)
%>

</body>
</html>

This would produce:

Conditions

Based on this, if you want to check whether a newly declared and uninitialized Boolean variable is false, you can omit the = False expression applied to it. Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim IsMarried As Boolean
    Dim TaxRate As Double

    TaxRate = 33.0
    If IsMarried Then TaxRate = 30.65

    Response.Write("Tax Rate: " & TaxRate & "%")
%>

</body>
</html>

This would produce:

Conditions

Notice that there is no = after the If IsMarried expression. In this case, the compiler assumes that the value of the variable is False. On the other hand, if you want to check whether the variable is True, make sure you include the = True expression. Overall, whenever in doubt, it is safer to always initialize your variable and it is safer to include the = True or = False expression when evaluating the variable:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim IsMarried As Boolean
        Dim TaxRate As Double

        TaxRate = 36.45 ' %

        IsMarried = True

        If IsMarried = False Then TaxRate = 33.15

        Response.Write("Tax Rate: " & TaxRate & "%")
%>

</body>
</html>

In the previous lesson, we introduced some Boolean-based functions such IsNumeric and IsDate. The default value of these functions is true. This means that when you call them, you can omit the = True expression.

If-Condition Based Functions

 

Choosing a Value

We have learned how to check whether a condition is True or False and take an action. Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim Status As UShort, EmploymentStatus As String

        Status = 1
        EmploymentStatus = "Unknown"

        If Status = 1 Then
            EmploymentStatus = "Full Time"
        End If

        Response.Write("Employment Status: " & EmploymentStatus)
%>

</body>
</html>

This would produce:

If

To provide an alternative to this operation, the Visual Basic language provides a function named Choose. Its syntax is:

Public Function Choose( _
   ByVal Index As Double, _ 
   ByVal ParamArray Choice() As Object _
) As Object

This function takes two required arguments. The fist argument is equivalent to the ConditionToCheck of our If...Then formula. For the Choose() function, this first argument must be a number (a Byte, an SByte, a Short, a UShort, an Integer, a UInteger, a Long, a ULong, a Single, a Double, or a Decimal value). This is the value against which the second argument will be compared. Before calling the function, you must know the value of the first argument. To take care of this, you can first declare a variable and initialize it with the desired value. Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim Status As UShort

    Status = 1

    Choose(Status, ...)
%>

</body>
</html>

The second argument can be the Statement of our formula. Here is an example:

Choose(Status, "Full Time")

We will see in the next sections that the second argument is actually a list of values and each value has a specific position referred to as its index. To use the function in an If...Then scenario, you pass only one value as the second argument. This value/argument has an index of 1. When the Choose() function is called in an If...Then implementation, if the first argument holds a value of 1, the second argument is validated.

When the Choose() function has been called, it returns a value of type Object. You can retrieve that value, store it in a variable and use it as you see fit. Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim Status As UShort, EmploymentStatus As String

    Status = 1

    EmploymentStatus = Choose(Status, "Full Time")

    Response.Write("Employment Status: " & EmploymentStatus)
%>

</body>
</html>

This would produce:

Conditions

Switching to a Value

To give you another alternative to an If...Then condition, the Visual Basic language provides a function named Switch. Its syntax is:

Public Function Switch( _
    ByVal ParamArray VarExpr() As Object _
) As Object
In the .NET Framework, there is another Switch implement that can cause a conflict when you call the Switch() function in your program. Therefore, you must qualify this function when calling it. To do this, use Microsoft.VisualBasic.Switch.

This function takes one required argument. To use it in an If...Then scenario, pass the argument as follows:

Switch(ConditionToCheck, Statement)

In the ConditionToCheck placeholder, pass a Boolean expression that can be evaluated to True or False. If that condition is true, the second argument would be executed.

When the Switch() function has been called, it produces a value of type Object (such as a string) that you can use as you see fit. For example, you can store it in a variable. Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
    Dim Status As UShort, EmploymentStatus As String

    Status = 2
    EmploymentStatus = "Unknown"

    EmploymentStatus = Microsoft.VisualBasic.Switch(Status = 1, "Full Time")

    Response.Write("Employment Status: " & EmploymentStatus)
%>

</body>
</html>

In this example, we used a number as argument. You can also use another type of value, such as an enumeration. Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<script language="vbscript" type="text/vbsscript" runat="server">

Private Enum EmploymentStatus
        FullTime
        PartTime
        Contractor
        Seasonal
        Unknown
End Enum

</script>
<title>Exercise</title>

</head>
<body>

<%
    Dim Status As EmploymentStatus
    Dim Result As String

    Status = EmploymentStatus.FullTime
    Result = "Unknown"

    Result = Microsoft.VisualBasic.Switch( _
			Status = EmploymentStatus.FullTime, "Full Time")

    Response.Write("Employment Status: " & Result)
%>

</body>
</html>

What Else When a Condition is True/False?

 

The If...Then...Else Condition

The If...Then statement offers only one alternative: to act if the condition is true. Whenever you would like to apply an alternate expression in case the condition is false, you can use the If...Then...Else statement. The formula of this statement is:

If ConditionToCheck Then
    Statement1
Else
    Statement2
End If

When this section of code is executed, if the ConditionToCheck is true, then the first statement, Statement1, is executed. If the ConditionToCheck is false, the second statement, in this case Statement2, is executed.

Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim MemberAge As Int16
        Dim MemberCategory As String

        MemberAge = 16

        If MemberAge <= 18 Then
            MemberCategory = "Teen"
        Else
            MemberCategory = "Adult"
        End If

        Response.Write("Membership: " & MemberCategory)
%>

</body>
</html>

This would produce:

Conditions

 
 
 
 

If...Then...Else-Condition Based Functions

 

Immediate If

To assist you with checking a condition and its alternative, the Visual Basic language provides a function named IIf. Its syntax is:

Public Function IIf( _
   ByVal Expression As Boolean, _ 
   ByVal TruePart As Object, _ 
   ByVal FalsePart As Object _ 
) As Object

This function operates like an If...Then...Else condition. It takes three required arguments and returns a result of type Object. This returned value will hold the result of the function.

The condition to check is passed as the first argument:

  • If that condition is true, the function returns the value of the TruePart argument and the last argument is ignored
  • If the condition is false, the first argument is ignored and the function returns the value of the second argument

As mentioned already, you can retrieved the value of the right argument and assign it to the result of the function. The expression we saw early can be written as follows:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim MemberAge As Int16
        Dim MemberCategory As String

        MemberAge = 16

        MemberCategory = IIf(MemberAge <= 18, "Teen", "Adult")

        Response.Write("Membership: " & MemberCategory)
%>

</body>
</html>

This would produce the same result we saw earlier.

Choose an Alternate Value

We saw how to call a function named Choose where only one value is being considered. The reality is that if there is an alternate value, the function produces a null result. Consider the same program we used earlier but with a different value:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim Status As UShort, EmploymentStatus As String

        Status = 2

        EmploymentStatus = Choose(Status, "Full Time")

        Response.Write(EmploymentStatus)
%>

</body>
</html>

The function returns nothing (an empty string). To use this function as an alternative to the If...Then...Else operation, you can pass two values for the second argument. The second argument is actually passed as a list of values. Each value has a specific position as its index. To use the function in an If...Then...Else implementation, pass two values for the second argument. Here is an example:

Choose(Status, "Full Time", "Part Time")

The second argument to the function, which is the first value of the Choose argument, has an index of 1. The third argument to the function, which is the second value of the Choose argument, has an index of 2. 

When the Choose() function is called, if the first argument has a value of 1, then the second argument is validated. If the first argument has a value of 2, then the third argument is validated. As mentioned already, you can retrieve the returned value of the function and use it however you want. Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<title>Exercise</title>

</head>
<body>

<%
        Dim Status As UShort, EmploymentStatus As String

        Status = 2

        EmploymentStatus = Choose(Status, "Full Time", "Part Time")

        Response.Write("Employment Status: " & EmploymentStatus)
%>

</body>
</html>

This would produce:

Conditions

Switching to an Alternate Value

We saw earlier how to call the Switch function in an If...Then condition. Once again, the problem is that if you call it with a value that is not checked by the first argument, the function produces a null value (an empty string). To apply this function to an If...Then...Else scenario, you can call it using the following formula:

Switch(Condition1ToCheck, Statement1, Condition2ToCheck, Statement2)

In the Condition1ToCheck placeholder, pass a Boolean expression that can be evaluated to True or False. If that condition is true, the second argument would be executed. To provide an alternative to the first condition, pass another condition as Condition2ToCheck. If the Condition2ToCheck is true, then Statement2 would be executed. Once gain, remember that you can get the value returned by the Switch function and use it. Here is an example:

<%@ Page Language="VB"  %>

<html>
<head>

<script language="vbscript" type="text/vbsscript" runat="server">

Private Enum EmploymentStatus
        FullTime
        PartTime
        Contractor
        Seasonal
        Unknown
End Enum

</script>
<title>Exercise</title>

</head>
<body>

<%
        Dim Status As EmploymentStatus
        Dim Result As String

        Status = EmploymentStatus.PartTime
        Result = "Unknown"

        Result = Microsoft.VisualBasic.Switch( _
                    Status = EmploymentStatus.FullTime, "Full Time", _
                    Status = EmploymentStatus.PartTime, "Part Time")

        Response.Write("Employment Status: " & Result)
%>

</body>
</html>

 

 
 
   
 

Previous Copyright © 2009-2010 FunctionX Next