# Part 4.2If statements

A program cannot be a complete program if it does not include some kind of useful functionality. One of the most useful pieces of code in any programming language is the if statement.

## Building an if statement

An if statement is a way of checking a value against another. VB.NET makes it easy to write if statements as they follow a simple system.

There are two 'essentials of if statements' in VB.NET that are known as If and Then. Both of these sub statements compose an If Statement when used. An additional part of an if statement that is not necessarily required is End If.

The following code sample demonstrates the structure of a standard if statement:

VB.NET
If x ? y Then
'Do something here
End If


Where x and y represent some variables and ? represents some operator.

If statements can also be written in a shorter and neater form, that removes the End If from the code.

The following sample demonstrates a shorter if statement.

VB.NET
If x ? y Then MsgBox ("Do something here")


Although this form of if statement is far more elegant, it prevents multiline code being used.

If statements always compare on a boolean basis. This means that any integer compared to another integer will return some boolean. The same occurs with strings. Any form of comparison follows this system.

Most if statements take the first form. This tends to be because it allows comments and multiline code within it. For the first if statement, it can be argued that there are three essentials of the if statement in VB.NET.

## Else

Else is an optional path. This path is followed when the if statement returns a false statement. It can be seen as if X does not happen then follow a line of code.

Else is simply written as a single line with the keyword Else.

VB.NET
If a = 1 Then
MsgBox("Yes")
Else
MsgBox("No")
End If


It can also be placed into a single line if statement as well.

VB.NET
If a = 1 Then MsgBox("Yes") Else MsgBox("No")


## ElseIf

Else if occurs when an else statement occurs but does a check before just assuming that path is correct.

ElseIf in VB.NET must be placed before an Else path as it must execute prior to it. An else if works similar to nesting an if statement within an else of an if statement as shown below:

VB.NET
If a = 1 Then
MsgBox("Yes")
Else
If a = 2 Then
MsgBox("Yes")
Else
MsgBox("No")
End If
End If


However, using an else if is much neater as shown below:

VB.NET
If a = 1 Then
MsgBox("Yes")
ElseIf a = 2
MsgBox("Yes")
Else
MsgBox("No")
End If


Also, there can be an infinite number of ElseIf statements within an if statement.

Code preview
Feedback 👍
Comments are sent via email to me.