Boolean, Integer. Logically, a Boolean of True could be represented as an Integer with a value of 1. And False could mean 0. In VB.NET we can implement this logic with Convert.ToInt32.
And just as ToInt32 converts to an Integer, the Convert.ToBoolean function goes from Integer to Boolean. The Convert class is helpful for these simple value-type conversions.
Part 4 We can use Convert.ToBoolean to convert from an Integer to a Boolean. We convert 1 to true here.
Part 5 For all values other than 0, Convert.ToBoolean will return true. Here 0 is converted to false.
Module Module1
Sub Main()
' Part 1: convert true to 1.
Dim value as Boolean = true
Dim result = Convert.ToInt32(value)
Console.WriteLine(result)
' Part 2: convert false to 0.
Dim value2 as Boolean = false
Dim result2 = Convert.ToInt32(value2)
Console.WriteLine(result2)
' Part 3: use If/Else to handle boolean conversion.
Dim value3 as Boolean = true
Dim result3 as Integer = 0
If value3 = True
result3 = 1
Else
result3 = 0
End If
Console.WriteLine(result3)
' Part 4: convert Integer to a Boolean.
Dim value4 as Integer = 1
Dim result4 as Boolean = Convert.ToBoolean(value4)
Console.WriteLine(result4)
' Part 5: convert Integer with 0 to False.
Dim value5 as Integer = 0
Dim result5 as Boolean = Convert.ToBoolean(value5)
Console.WriteLine(result5)
End Sub
End Module1
0
1
True
False
ToBoolean notes. In testing, Convert.ToBoolean will convert the Integer 0 into false. But all other values, such as -1 and 2 will be converted into true.
So Zero means false, but all other numbers are true according to Convert.ToBoolean.
Summary. Using the Convert.ToInt32 function, as well as Convert.ToBoolean, is usually best for Boolean and Integer conversions. But If-Else statements can sometimes be helpful as well.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.