Booleans and numerics

Posted Sun, Jul 20 2008 0:22 by bill

I was reading Kathleen’s post about what a C# developer needs to know about VB and thought I should clarify the bit about Booleans converted to numerics.  A Boolean in VB when converted to an integer type numeric, will be zero or the bitwise Not of zero.

This table summarizes the value of True when converted to integer types using VB’s built  in CType operator, or specific operator:

Type CLR Type Hex value Decimal specific operator
Byte Byte &HFF 255 CByte
Short Int16 &HFFFF -1 CShort
Integer Int32 &HFFFFFFFF -1 CInt
SByte SByte &HFF -1 CSByte
UShort UInt16 &HFFFF 65535 CUShort
UInteger UInt32 &HFFFFFFFF 4294967295 CUInt
ULong Uint64 &HFFFFFFFFFFFFFFFF 18446744073709551615 CULng


As you can see, the Hex values are all bits set.

It’s up to you if you use the more succinct specific operator, such as CInt(value), rather than CType(vale, Int32).  I tend to use Cint.  I do go out of my way to use CUInt … I’ll let you guess why ;)

For C# people, living in a world devoid of such niceties, you can continue to rely heavily on the Convert class, even if the result is incorrect as far as bitwise representation goes ;)

And for more insight into operators in VB, see my article in Visual Studio Magazine.

Filed under: , , , ,