I have the following
if()
statement:
if( _hexColourString.Length >= 8 )
_bytes[ 3 ] = byte.Parse( _hexColourString.Substring( start + 6, 2 ), NumberStyles.AllowHexSpecifier );
else
_bytes[ 3 ] = 0x00;
If I try to express this using the ternary operator, I get an error saying I cannot implicitly convert an
int
to a
byte
. The following does NOT compile:
_bytes[ 3 ] = ( _hexColourString.Length >= 8 ) ? byte.Parse( _hexColourString.Substring( start + 6, 2 ), NumberStyles.AllowHexSpecifier ) : 0x00;
So I thought I'd check which half of the ternary assignment was giving the problem. I took out the conditional part of the statement and wrote the two assignments as separate statements, like this:
_bytes[ 3 ] = byte.Parse( _hexColourString.Substring( start + 6, 2 ), NumberStyles.AllowHexSpecifier );
_bytes[ 3 ] = 0x00;
Both of these compile. The ternary operator seems to be changing the implicit type of one of the assignments (the literal
0x00
).
Why does the plain assignment
_bytes[ 3 ] = 0x00;
compile okay without a cast but requires one when the expression is part of a ternary operator?
What I have tried:
As a final sanity check, I wanted to see conclusively which side of the assignment was causing the problem. I suspected the literal hex byte and I appear to be correct. The following pointless statement compiles:
_bytes[ 3 ] = ( _hexColourString.Length >= 8 ) ? byte.Parse( _hexColourString.Substring( start + 6, 2 ), NumberStyles.AllowHexSpecifier ) :
byte.Parse( _hexColourString.Substring( start + 6, 2 ), NumberStyles.AllowHexSpecifier );
But the following equally pointless statement does NOT compile:
_bytes[ 3 ] = ( _hexColourString.Length >= 8 ) ? 0x00 : 0x00;