Visual Basic If Statement

If you have programmed before in languages like C#, PHP, or JavaScript, then you will be familiar with If Statements. An If Statement is simply a decision statement, and the code contained inside it will execute if the condition evaluates to true.

Syntax

  If condition Then
         'Your code here..
        End If

Tip: In the VS studio IDE, if you type if until it’s highlighted and then hit tab twice, the syntax will automatically be inserted.

Create a new VB Console Application and name it If Statements. Then copy the following:

  Sub Main()

        Dim age As Integer

        Console.WriteLine("Please enter your age:")
        age = Console.ReadLine().ToString()

        If age = 15 Then
            Console.WriteLine("You are not old enough to drink")
        End If

        Console.ReadLine()

    End Sub

Code Explained:

  • First we created a variable called “age” with the data type integer.
  • Next we printed to the console: “Please enter your age:”
  • We then read the user’s value.
  • If you enter 15 you will see the message: “You are not old enough to drink”.
  • If you enter any other value the program will just terminate without any notification.

This is a simple If Statement. The problem with this If Statement is that if the condition evaluates to false (the age is not 15), the program will do nothing. In this case we can use an If Else Statement.

If Else

Syntax

  If condition Then
          code
        Else
           other code
        End If

Comment out the other If Statement (CTRL+K+C) and copy the following code:

        Dim username As String
        Dim password As Integer

        username = Nothing
        password = Nothing

        Console.WriteLine("Enter Your UserName")
        username = Console.ReadLine()
        Console.WriteLine("Enter Your Password")
        password = Console.ReadLine()

        If username = "Asim" And password = 243 Then
            Console.WriteLine("Welcome Asim!")
        Else
            Console.WriteLine("Access is denied")
        End If

        Console.ReadLine()

This is similar to the above If Statement. You have two variables (string/integer) which we use to store the values the user enters when prompted. Then we compare those values to the values in our If Statement. So if username = “Asim” AND password = 243, then “Welcome Asim” is displayed; otherwise “Access Denied” is displayed. You are also using the logical operator And which will be explained later.

Nested If Else

You can also have a nested If Else Statement.

   Dim message As String

        message = "Welcome " & username

        If username = "Asim" And password = 243 Then
            Console.WriteLine(message)
        Else
            If username = "Dave" And password = 12345 Then
                Console.WriteLine(message)
            Else
                If username = "Admin" And password = 2012 Then
                    Console.WriteLine(message)
                Else
                    Console.WriteLine("Oops could not find you!")
                End If
            End If
        End If

The process is the same as before, but we have more decisions. However, we have made a new string variable called “message”; this was made to avoid repeating the console message. The If Else Statement will see if the statements are true: if they are it will print out the correct message, and if they are false it will print the last message. If Else Statements can become quite long, so it is best to use a Select Case Statement which will be addressed in the next lesson.

If Else Statement Operators

There are various operators you can use with If Else Statements:

Operator Description Example
< Less than operator if 19 < 20 Then
> Greater than operator if 20 > 19 Then
= Equal to operator if a = b Then
<> Not equal to operator if a <> b Then
<= Less than or equal to operator if 19 <= b Then
>= Greater than or equal to operator if 19 >= b Then

Example of Less Than

 If 15 < 20 Then
    Console.WriteLine("15 is greater than 20!")
  End If

 Console.ReadLine()

In this example the condition is simply asking “Is 15 less than 20?” Since this is true, the If Statement will execute.

Example of Not Equal To

 Dim name As String
 name = "Adam"

 If name <> "Asim" Then
    Console.WriteLine("Name does not equal Asim, Name = " + name)
 End If
 
 Console.ReadLine()

In this example, the condition is saying “If name NOT EQUAL TO Asim.” Since the variable “name” does not equal Asim, the condition is true and the If Statement will execute.

Logical Operators

You can use the logical operators to extend the If Else Statements and use two conditions, for example if a = b And a > 19 Then

Operator Description
And And Operator – If both conditions are true, then the result is true
Or Or Operator – If either of the conditions are true, the result will be true
Not Not Operator – If the condition is false, then the result will be true, or vice versa.

Example of Logical And Operator

  Dim a As Integer
  Dim rnd As New Random
  a = rnd.Next(90, 160)

  If a > 100 And a < 150 Then
     Console.WriteLine("A is greater than 100, but less than 150, A = " + a.ToString())
  End If

        Console.ReadLine()

The only difference with this example is we are using the random class to generate a random number between 90 – 160, which is assigned to the variable A. Then the If Statements condition is, “Is A greater than 100 AND less than 150?” If it is, it will continue to execute the If Statement; otherwise it will terminate.

Summary

In this tutorial you have learned about If Statements, If Else Statements and Nested If Else statements.  In addition, you have learned how to use the Conditional and Logical operators to perform more actions based on various conditions.