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:
From the docs:
Byte’s aren’t signed, so you get 255 instead from Two’s Compliment.