Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Boolean to Integer in VB.NET

Tags:

vb.net

Take the following code:

Sub Main()      Dim i As Integer     Dim b As Boolean      i = 1     b = i     i = b     Console.WriteLine(i)      i = Convert.ToInt32(b)     Console.WriteLine(i)  End Sub 

This prints the following:

-1 1 

Why is this?

(Just a joke :) You can get 0 too...

Int32.TryParse("True", i) Console.WriteLine(i) 
like image 537
Prankster Avatar asked Apr 13 '09 20:04

Prankster


2 Answers

What you're seeing is a bit of legacy code showing its head.

At the heart of the matter is the VT_BOOL type. Visual Basic 6.0 used the VT_BOOL type (AKA VARIANT_BOOL) for its boolean values. True for a VARIANT_BOOL is represented with the value VARIANT_TRUE which has the integer value -1. During the conversion to .NET it was decided that when using Visual Basic conversion routines to convert a boolean value to an Integer value, Visual Basic 6.0 semantics would be maintained on the return value; it would be -1.

The first implicit conversion occurs with the b = i line. Under the hood this does an implicit conversion from integer to boolean. Any non-zero value is deemed to be true, therefore the resulting value is true.

However, the following line of code is doing an implicit conversion to an integer type.

i = b 

Under the hood this uses one of the Visual Basic conversion routines (CType or CInt) to convert the value to an integer. As such Visual Basic semantics are in play and the value returned is -1.

The next interesting line is the Convert.ToInt32() line. This is using a .NET conversion routine which does not use Visual Basic semantics. Instead, it returns the underlying BCL representation for a true boolean value which is 1.

like image 53
JaredPar Avatar answered Sep 20 '22 14:09

JaredPar


Some languages consider boolean true to be -1 rather than 1. I'd have to do research to see why, as I don't recall.

In VB6, the constant True has the value -1.

However, Convert.ToInt32(Boolean) is documented as returning "The number 1 if value is true; otherwise, 0." That way, it's the same no matter which framework language you're using.

Edit: See the question boolean true -- positive 1 or negative 1

like image 44
Powerlord Avatar answered Sep 22 '22 14:09

Powerlord