Nesting of If Statements in Visual Basic .Net

Visual Basic .Net supports the nesting of If statements, in which we can use If…Then statements within If…Then statements. This is called Nested If statements. This is very useful if we have more than one conditions to check.

Syntax

If (condition) Then
     If (condition 2) Then
            [statement x]
     End If
End If

The if condition 2 will check only if the condition 1 is true and the statement x will be executed only if both the condition 1 and condition 2 is true.

Example

If a > b Then
     If a > c Then
         larger = a
     End If
End If

Example Program

The below program will give you more idea about Nesting of If statements.

Module Module1

   Sub Main()
      Dim a, b, c, larger As Integer
      a = 10
      b = 8
      c = 5
      If a > b Then
         If a > c Then
            larger = a
         End If
      End If
      Console.WriteLine(larger)
   End Sub

End Module

The result of the above program will be 10. And the larger is a.