HomeSearch

VB.NET Boolean, True, False and Not (Return True)

Use the Boolean type to represent a True or False value. Test Booleans in If-statements.
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.Keywords
Example. We assign a Boolean variable to True or False. Next, we 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.If Then

Finally: We store the result of an expression in a Boolean variable. This clarifies some logic.

VB.NET program that uses Boolean 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
Expressions. 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 only with a Boolean value.

Tip: You can assign an expression that evaluates to True or False directly to a Boolean variable as well.

Further: Storing a complex expression's result in a Boolean can be used as an optimization, as it will only be evaluated once.

Return 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.

Note: If the List has a Length of 0, IsEmpty returns True. Otherwise False is returned.

VB.NET program that uses Boolean return value 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 Module Output True False
Summary. We took a quick look at the Boolean type in the VB.NET programming language. With Boolean, you can store True and False and also the result of expressions that evaluate to True or False.

Tip: Booleans are necessary for If and ElseIf statements, and careful use of them can make your programs clearer and faster.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls