Boolean
A Boolean
stores a value indicating True or False. It can be used as an expression in an If
-statement. It can also store the result of an expression.
Booleans are used throughout VB.NET programs. We can return a Boolean
from a function, or pass a Boolean
as an argument.
Boolean
exampleWe assign a Boolean
variable to True or False. Then we use Booleans in a variety of ways in this simple program.
Boolean
: change True to False and False to True.Boolean
can be used as an expression in an If
-statement. We store the result of an expression variable.Boolean
values and expressions can be used interchangeably. An If
-statement can test a Boolean
directly.Boolean
variable as well.Module Module1 Sub Main() Dim value As Boolean = True Console.WriteLine(value) ' Part 1: flip the boolean. value = Not value Console.WriteLine(value) ' Part 2: this if-statement evaluates to false. If (value) Then Console.WriteLine("A") End If ' Part 3: evaluates to true. If (Not value) Then Console.WriteLine("B") End If ' Part 4: store expression result. Dim result As Boolean = Not value And 1 = Integer.Parse("1") Console.WriteLine(result) End Sub End ModuleTrue False B True
Boolean
A Function can return True or False. We can even return the result of an expression that evaluates to True or False. Here in IsEmpty
we return an expression's result.
List
has a Length
of 0, IsEmpty
returns True. Otherwise False is returned.Module Module1 Dim _values As List(Of String) = New List(Of String) Function IsEmpty() As Boolean ' Return a boolean value. ' ... This returns true if the Count is equal to 0. ' ... It returns false otherwise. Return _values.Count = 0 End Function Sub Main() ' Use the IsEmpty boolean method. Console.WriteLine(IsEmpty()) ' Add an element to the List and call IsEmpty again. _values.Add("bird") Console.WriteLine(IsEmpty()) End Sub End ModuleTrue False
We examined the Boolean
type in VB.NET. 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.