Why does casting a boolean
to a byte
in .NET give the following output?
Code Snippit:
Dim x As Boolean = 1
Dim y As Byte = x 'Implicit conversion here from Boolean to Byte
System.Diagnostics.Debug.Print( _
"x = " & x.ToString _
& " y = " & y.ToString _
& " (bool)(1) = " & CType(1, Boolean).ToString _
& " (byte)((bool)1) = " & CType((CType(1, Boolean)), Byte).ToString)
Output:
x = True
y = 255
(bool)(1) = True
(byte)((bool)1) = 255
Why does True
(which commonly is referred to as an integer representation of 1) convert to 255 when casted to a byte
?
The VB.NET compiler handles it as a narrowing conversion. From the 10.0 VB.NET Spec:
Narrowing conversions are conversions that cannot be proved to always succeed, conversions that are known to possibly lose information, and conversions across domains of types sufficiently different to merit narrowing notation. The following conversions are classified as narrowing conversions:
- From Boolean to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
From the docs:
When Visual Basic converts numeric data type values to Boolean, 0 becomes False and all other values become True. When Visual Basic converts Boolean values to numeric types, False becomes 0 and True becomes -1.
Byte's aren't signed, so you get 255 instead from Two's Compliment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With