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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.