Boolean Variables

The Boolean data type stores True/False values. Boolean variables are, in essence, integers that take the value –1 (for True) and 0 (for False). Actually, any nonzero value is considered True. Boolean variables are declared as

Dim result As Boolean

and they are initialized to False. Even so, it’s a good practice to initialize your variables explicitly, as in the following code segment. Boolean variables are used in testing conditions, such as the following:

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim result As Boolean = True

        If result Then
            MsgBox("you cleared exams")
        End If

    End Sub
End Class

They are also combined with the logical operators And, Or, Not, and Xor. The Not operator toggles the value of a Boolean variable. The following statement is a toggle:

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim result As Boolean = True

        If result = True Then
            result = False
        Else
            result = True
        End If
    End Sub
End Class

Boolean operators operate on Boolean variables and return another Boolean as their result. The following statements will display a message if one (or both) of the variables ReadOnly and Hidden are True (in the following example, the ReadOnly and Hidden variables might represent the corresponding attributes of a file):

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim FileReadOnly As Boolean
        Dim FileHidden As Boolean

        FileReadOnly = False
        FileHidden = False

        If FileReadOnly Or FileHidden Then
            MsgBox("Couldn’t open the file")
        Else
            MsgBox("file is ready to be opened")
        End If

    End Sub
End Classc