Casting a boolean to an integer returns -1 for true?

前端 未结 9 781
醉梦人生
醉梦人生 2020-12-01 05:30

I am working with some VB.NET code that seems to be casting a boolean value to an integer using CInt(myBoolean). The odd thing that is happening is that it retu

相关标签:
9条回答
  • 2020-12-01 05:56

    I tested it and got the following results:

    Public Module BooleanTest
    Public Function GetTrue() As Boolean
        GetTrue = True
    End Function
    End Module
    

    ...

    [StructLayout(LayoutKind.Explicit)]
    struct MyStruct
    {
        [FieldOffset(0)]
        public bool MyBool;
        [FieldOffset(0)]
        public int MyInt32;
    }
    
    static void Main(string[] args)
    {
        MyStruct b1, b2;
        b1.MyInt32 = 0;
        b2.MyInt32 = 0;
        b1.MyBool = BooleanTest.BooleanTest.GetTrue();
        b2.MyBool = true;
        Console.WriteLine(b1.MyInt32);
        Console.WriteLine(b2.MyInt32);
    }
    

    This will result in:

    1
    1

    I hope this proves that all True values inside .NET are always the same. The reason is simple: All .NET members have to communicatie with each other. It would be weird if object.Equals(trueFromCSharp, trueFromVB) would result in false (as will trueFromCSharp == trueFromVB).

    CInt is just a function which will convert True into -1. Another function Int will return 1. But these are converters, and do not say anything about the binary values.

    0 讨论(0)
  • 2020-12-01 05:59

    It seems like a gotcha, and I don't know any other examples of this behaviour.

    http://msdn.microsoft.com/en-us/library/ae382yt8.aspx specifies this behaviour, with a "Don't do that, mkay" sorta remark with it. Do note further down:

    Conversion in the Framework

    The ToInt32 method of the Convert class in the System namespace converts True to +1.

    If you must convert a Boolean value to a numeric data type, be careful about which conversion method you use.

    0 讨论(0)
  • 2020-12-01 06:01

    The MSDN documentation provides some valuable insight:

    Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers. You should never write code that relies on equivalent numeric values for True and False. Whenever possible, you should restrict usage of Boolean variables to the logical values for which they are designed.

    0 讨论(0)
提交回复
热议问题