C# byte type and literals

The following code works.

byte b = 1;

But I noticed the following code doesn't work

byte b = BooleanProperty ? 2 : 3; // error

The compiler says

Cannot convert source type 'int' to target type 'byte'

I understand that int type cannot be converted to byte type implicitly. But why the former code works, and the latter doesn't?

Jon Skeet
people
quotationmark

There's an implicit conversion from int constants (not just literals, but any compile-time constant expression of type int) to byte, so long as the value is in range. This is from section 6.1.9 of the C# 5 specification:

An implicit constant expression conversion permits the following conversions:

  • A constant-expression (ยง7.19) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.

However, there's no implicit conversion from a "general" expression of type int to byte - and that's what you've got in your second case. It's a bit like this:

int tmp = BooleanProperty ? 2 : 3;
byte b = tmp; // Not allowed

Note that the use of the conditional expression doesn't play any part in inferring its type - and as both the second and third operands are of type int, the overall expression is of type int as well.

So if you understand why the snippet above where I've separated the code into two statements doesn't compile, that explains why your single-line version with the conditional doesn't either.

There are two ways of fixing it:

  • Change the second and third operands to expressions of type byte so that the conditional expression has an overall type of byte:

    byte b = BooleanProperty ? (byte) 2 : (byte) 3;
    
  • Cast the result of the conditional expression:

    byte b = (byte) (BooleanProperty ? 2 : 3);
    

people

See more on this question at Stackoverflow