1

So I'm trying to set a byte based on a boolean value I'm receiving from a view. I want to do it inline so it looks neater but for some reason it throws an "Cannot implicitly convert type int to byte" but when I try it with the traditional if else statement, it is working fine.

Can someone explain to me why this is happening?

        byte byteFlag1;

        byteFlag1 = boolFlag ? 1 : 0;
        // this throws an error


        byte byteFlag2;
        if( boolFlag )
        {
            byteFlag2= 1;
        } else
        {
            byteFlag2= 0;
        }
         // this works fine?

1 Answers1

1

There is no implicit conversion from an integer to a byte. This is necessary as not all integers have a valid byte that they can be converted to.

There is a conversion from every numeric literal to any numeric type for which it is a valid value. This conversion will always be valid by definition, if it wasn't, you'd have a compile time error indicating as much.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • why is one considered an integer and one is considered a numeric literal in the above context? –  Mar 05 '18 at 21:35
  • I'm guessing the interesting part is why the complier can't figure out this when using the conditional operator – user6144226 Mar 05 '18 at 21:35
  • 1
    @JoeViscardi One is a numeric literal because...it's a number, and that's a numeric literal (by definition). One isn't, because you performed an operation on it that wasn't resolved at compile time, making it no longer a literal. – Servy Mar 05 '18 at 21:36
  • 1
    @user6144226 So in the first example what value is going to be assigned to `byteFlag1`? Will it be a 1 or a 2? – Servy Mar 05 '18 at 21:37
  • What is the operation being performed? –  Mar 05 '18 at 21:46
  • @JoeViscardi A conditional operation. – Servy Mar 05 '18 at 21:46
  • Is there a better way to do this without having to just implicitly pick which columns besides the one timestamp? I need to do this with over 100 tables and the code is all like how it was originally –  Mar 13 '18 at 19:21
  • @JoeViscardi You can use byte literals rather than integer literals, in the conditional operator, which means that no conversion from int to byte is ever needed. – Servy Mar 13 '18 at 19:25