If Else in Visual Basic .NET

Branching with If and Else in Visual Basic .NET is straightforward.

Imports System

Module Program
    Sub Main()
        ' Here's a basic example.
        If 7 Mod 2 = 0 Then
            Console.WriteLine("7 is even")
        Else
            Console.WriteLine("7 is odd")
        End If

        ' You can have an If statement without an Else.
        If 8 Mod 4 = 0 Then
            Console.WriteLine("8 is divisible by 4")
        End If

        ' Logical operators like AndAlso and OrElse are often
        ' useful in conditions.
        If 8 Mod 2 = 0 OrElse 7 Mod 2 = 0 Then
            Console.WriteLine("either 8 or 7 are even")
        End If

        ' A statement can precede conditionals; any variables
        ' declared in this statement are available in the current
        ' and all subsequent branches.
        Dim num As Integer = 9
        If num < 0 Then
            Console.WriteLine(num & " is negative")
        ElseIf num < 10 Then
            Console.WriteLine(num & " has 1 digit")
        Else
            Console.WriteLine(num & " has multiple digits")
        End If
    End Sub
End Module

To run the program, save it as IfElse.vb and use the Visual Basic .NET compiler:

$ vbc IfElse.vb
$ mono IfElse.exe
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Visual Basic .NET, you don’t need parentheses around conditions, but the Then keyword is required. Also, ElseIf is used instead of Else If for multiple conditions.

Visual Basic .NET does have a ternary operator-like construct called the If operator, which can be used for simple conditional expressions:

Dim result As String = If(someCondition, "True result", "False result")

This can be useful for basic conditions, but for more complex scenarios, a full If statement is often clearer and more readable.