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.
' Part 1: convert true to 1.
Dim value as Boolean = true
Dim result = Convert.ToInt32(value)
' Part 2: convert false to 0.
Dim value2 as Boolean = false
Dim result2 = Convert.ToInt32(value2)
' Part 3: use If/Else to handle boolean conversion.
Dim value3 as Boolean = true
Dim result3 as Integer = 0
If value3 = True
result3 = 1
result3 = 0
' Part 4: convert Integer to a Boolean.
Dim value4 as Integer = 1
Dim result4 as Boolean = Convert.ToBoolean(value4)
' Part 5: convert Integer with 0 to False.
Dim value5 as Integer = 0
Dim result5 as Boolean = Convert.ToBoolean(value5)
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.