VB.NET Boolean Use

The VB.NET programming language

You want to see some examples of the Boolean type in VB.NET programs. The Boolean type stores a value indicating True or False. It can be used as an expression in an If-statement, and can also store the result of an expression.

Example

Note

To start, you can assign a Boolean variable to True or False. Next, we show that you can use the Not operator to "invert" the value of the Boolean: change True to False and False to True. A Boolean can be used as an expression in an If or ElseIf statement. Finally, you can store the result of an expression in a Boolean variable.

This VB program uses the Boolean type. A Boolean holds True or False. It occupies 1 byte of memory.

Program that uses Boolean [VB.NET]

Module Module1
    Sub Main()
	Dim value As Boolean = True
	Console.WriteLine(value)

	' Flip the boolean.
	value = Not value
	Console.WriteLine(value)

	' This if-statement evaluates to false and thus isn't entered.
	If (value) Then
	    Console.WriteLine("A")
	End If

	' Evaluates to true.
	If (Not value) Then
	    Console.WriteLine("B")
	End If

	' Store expression result.
	Dim result As Boolean = Not value And 1 = Integer.Parse("1")
	Console.WriteLine(result)
    End Sub
End Module

Output

True
False
B
True

Booleans and expressions

Programming tip

Boolean values and expressions are closely linked: they both can be used interchangeably when they evaluate to True or False. This means you can use an If-statement with a Boolean value only. You can assign an expression that evaluates to True or False directly to a Boolean variable as well. Storing a complex expression's result in a Boolean can be used as an optimization, as it will only be evaluated once.

Summary

.NET Framework information

We took a quick look at the Boolean type in the VB.NET language. With Boolean, you can store True and False and also the result of expressions that evaluate to True or False. Booleans are necessary for If and ElseIf statements, and careful use of them can make your programs clearer and faster.

VB.NET Tutorials
.NET