Home
VB.NET
Convert Boolean to Integer
Updated Nov 9, 2023
Dot Net Perls
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.
Boolean
Integer
Example. 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.
Part 1 We have a Boolean called "value" and we pass it to the Convert.ToInt32 function. This transforms true into 1.
Part 2 Here we use Convert.ToIn32 and change the Boolean false into 0. So ToInt32 will return 0 or 1 for true and false arguments.
Part 3 Sometimes, particularly if additional processing is needed, it is helpful to just use an If-Else chain to convert a Boolean to an Integer.
If
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 Module
1 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.
This page was last updated on Nov 9, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen