Home
VB.NET
If, ElseIf, Else Examples
Updated Jun 20, 2024
Dot Net Perls
If Then, ElseIf. With logic (an If-statement) we direct control flow. The condition is evaluated. On a true result, control moves to the statements inside the block.
Expressions. In an If-statement, multiple expressions are short-circuited. We use And, Or, AndAlso and OrElse to evaluate conditions. With an End we close our block.
First example. An If-statement uses the If-keyword and the Then-keyword. The ElseIf-statement has the "If" part capitalized in the middle.
And The Else-statement has no "Then" part. We end a block with an "End If" statement.
Detail We do not use 2 equals signs together in an If-statement—we just use one.
Tip Visual Studio will automatically insert the "Then" and "End If" parts of an If-statement.
Module Module1

    Function Test(ByVal s As String) As Integer
        ' Check input with If, ElseIf and Else.
        If s = "cat" Then
            Return 1
        ElseIf s = "dog" Then
            Return 2
        Else
            Return 0
        End If
    End Function

    Sub Main()
        ' Call Test function.
        Console.WriteLine(Test("dog"))
        Console.WriteLine(Test("cat"))
        Console.WriteLine(Test("elephant"))
    End Sub

End Module
2 1 0
If Not. An If-statement can also test a negative. Instead we must apply the Not-keyword. The If-statement then reads "If not this, then."
Detail We also can apply the Not-keyword to the ElseIf clause. We cannot use the "!=" operator.
Module Module1
    Sub Main()
        ' An integer variable.
        Dim i As Integer = 100

        ' Test integer against 100 and 200.
        If Not i = 100 Then
            Console.WriteLine("i not 100")
        ElseIf Not i = 200 Then
            Console.WriteLine("i not 2")
        End If

    End Sub
End Module
i not 2
And, Or. With the "And" and "Or" keywords, we test complex expressions. These expressions are chained. Both And and Or will lead to the evaluation of all parts (no early termination).
Bitwise XOR
And Please consider the OrElse and AndAlso operators for early termination—this can lead to a performance improvement.
Module Module1

    Sub Main()
        Dim left As Integer = 10
        Dim right As Integer = 100

        ' Use "and" in expression.
        If left = 10 And right = 100 Then
            Console.WriteLine(1)
        End If

        ' Use "or" in expression.
        If left = 5 Or right = 100 Then
            Console.WriteLine(2)
        End If
    End Sub

End Module
1 2
OrElse. This is important—the OrElse operator supports short-circuiting with an Or operator. This program demonstrates the OrElse operator.
Note If we use Or instead of OrElse, both IsBird() and IsCat() will be executed in this VB.NET program.
Important If we want to finish the expression as soon as a true result is found, we must use OrElse.
Module Module1

    Function IsBird() As Boolean
        Console.WriteLine("IsBird returns true")
        Return True
    End Function

    Function IsCat() As Boolean
        Console.WriteLine("IsCat not reached")
        Return False
    End Function

    Sub Main()

        If IsBird() OrElse IsCat() Then
            Console.WriteLine("DONE")
        End If

    End Sub

End Module
IsBird returns true DONE
AndAlso. This operator is the version of And that supports short-circuiting (early termination). If a false value is encountered, things that come after AndAlso will not be tested.
Module Module1

    Function IsRed() As Boolean
        Console.WriteLine("IsRed: false")
        Return False
    End Function

    Function IsBlue() As Boolean
        Console.WriteLine("IsBlue: true")
        Return True
    End Function

    Sub Main()

        If IsRed() AndAlso IsBlue() Then
            Console.WriteLine("DONE")
        End If

    End Sub

End Module
IsRed: false
Boolean Function. An If-statement does not always directly test values. Sometimes it calls another Function and tests the value returned by that Function.
Function
Here The If-statement calls the IsValid Function. IsValid returns True if the Integer argument is within a certain range.
Boolean
So If the Integer is within the specified range (10 to 100 inclusive) the inner block of the If-statement is reached.
Module Module1

    ''' <summary>
    ''' See if size is valid.
    ''' </summary>
    Function IsValid(ByVal size As Integer) As Boolean
        ' Returns true if size is within this range.
        Return size >= 10 And size <= 100
    End Function

    Sub Main()
        ' Size variable.
        Dim size As Integer = 50

        ' Call IsValid function in an If-expression.
        If IsValid(size) Then
            Console.WriteLine("Valid size")
        End If
    End Sub

End Module
Valid size
Locals. If-statements can become complex and hard to understand. It is sometimes possible to simplify them by adding local variables.
Here We introduce a Boolean that stores whether the animal and size variables indicate a "big cat."
Then We can test the isBigCat variable in the two If-statements. This reduces code repetition and makes the program easier to read.
Also In some programs, we can use this approach to reduce expensive method calls by storing their results for later reuse.
Module Module1

    Sub Main()
        Dim animal As String = "cat"
        Dim size As Integer = 10
        Dim color As String = "grey"

        ' Store expression result in local variable.
        Dim isBigCat As Boolean = (animal = "cat" And size >= 8)

        ' Test local variable.
        If isBigCat And color = "grey" Then
            Console.WriteLine(True)
        End If

        If isBigCat And color = "white" Then
            Console.WriteLine(False)
        End If
    End Sub

End Module
True
Not equal operator. In VB.NET we can use the "not equals" operator instead of the "Not" keyword. This works in an if-statement or loops like the while-loop.
Tip This operator is available on Integers, Strings, Doubles and other types. It can help keep VB.NET code shorter.
Module Module1

    Sub Main()
        Dim temp As Integer = 10

        ' Use "not equal" operator.
        If temp <> 0 Then
            Console.WriteLine("Temp not zero")
        End If

        ' Inner statement not reached here.
        If temp <> 10 Then
            Console.WriteLine("???")
        End If
    End Sub

End Module
Temp not zero
Benchmark, reorder Ifs. Suppose we test values in an If-statement. If the most common encountered value is 3, we should put that test first. This reduces the number of checks required.
Version 1 This code tests the most commonly-encountered value last. So multiple checks must be done in the common case.
Version 2 This version checks the most common value first. It provides a "fast path" for the most frequent situation.
Result It is faster to check for the most common value first. Other optimizations, like Select Case, can be even better in performance.
Module Module1

    Sub Main()
        Dim m As Integer = 10000000
        Dim s1 As Stopwatch = Stopwatch.StartNew
        ' Version 1: test most common value last.
        For i As Integer = 0 To m - 1
            Version1(100, 3)
        Next
        s1.Stop()

        Dim s2 As Stopwatch = Stopwatch.StartNew
        ' Version 2: test most common value first.
        For i As Integer = 0 To m - 1
            Version2(100, 3)
        Next
        s2.Stop()

        Dim u As Integer = 1000000
        Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
        Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
    End Sub

    Function Version1(ByVal max As Integer, ByVal test As Integer) As Integer
        ' Test 3 last.
        Dim result As Integer = 0
        For i As Integer = 0 To max - 1
            If test = 1 Then
                result += 1
            ElseIf test = 2 Then
                result -= 1
            ElseIf test = 3 Then
                result += 2
            End If
        Next
        Return result
    End Function

    Function Version2(ByVal max As Integer, ByVal test As Integer) As Integer
        ' Test 3 first.
        Dim result As Integer = 0
        For i As Integer = 0 To max - 1
            If test = 3 Then
                result += 2
            ElseIf test = 1 Then
                result += 1
            ElseIf test = 2 Then
                result -= 1
            End If
        Next
        Return result
    End Function

End Module
114.63 ns Test 1, 2, 3 (3 last) 89.32 ns Test 3, 1, 2 (3 first)
Summary. If-statements are used throughout programs. They use a slightly different syntax form from many languages. We use the Not-keyword to test negatives for truth.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 20, 2024 (edit link).
Home
Changes
© 2007-2025 Sam Allen