Boolean
, IntegerLogically, 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.
It is not possible to convert from a Boolean
to an Integer in VB.NET with just casting (like TryCast
). Instead we must use the Convert class
.
Boolean
called "value" and we pass it to the Convert.ToInt32
function. This transforms true into 1.Convert.ToIn32
and change the Boolean
false into 0. So ToInt32
will return 0 or 1 for true and false arguments.If
-Else chain to convert a Boolean
to an Integer.Convert.ToBoolean
to convert from an Integer to a Boolean
. We convert 1 to true here.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
notesIn testing, Convert.ToBoolean
will convert the Integer 0 into false. But all other values, such as -1 and 2 will be converted into true.
Convert.ToBoolean
.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.