Conditional operator cannot cast implicitly?

前端 未结 3 1712
再見小時候
再見小時候 2020-11-22 07:14

I\'m a little stumped by this little C# quirk:

Given variables:

Boolean aBoolValue;
Byte aByteValue;

The following compiles:

<
3条回答
  •  遥遥无期
    2020-11-22 07:48

    I'm using VS 2005, for and I can reproduce, for bool & Boolean, but not for true

     bool abool = true;
     Boolean aboolean = true;
     Byte by1 = (abool ? 1 : 2);    //Cannot implicitly convert type 'int' to 'byte'
     Byte by2 = (aboolean ? 1 : 2); //Cannot implicitly convert type 'int' to 'byte'
     Byte by3 = (true ? 1 : 2);     //Warning: unreachable code ;)
    

    The simplest workaround seems to be this cast

     Byte by1 = (Byte)(aboolean ? 1 : 2);
    

    So, yes, it seems that the ternary operator is causing the constants to "fix" their types as ints and disable the implicit type conversion that you would otherwise get from constants that fit within the smaller type.

提交回复
热议问题