Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need an extra cast when using the conditional operator? [duplicate]

In C# I can assign a number (up to 255) directly to a variable of type byte:

byte red = 255;

However if I do this in a more complex statement with a conditional operator:

byte red = (redNode != null) ? byte.Parse(redNode.Value) : 255;

I get an error: "CS0266 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)".

I need to explicitly do the cast to byte for the 255:

byte red = (redNode != null) ? byte.Parse(redNode.Value) : (byte)255;

Why is this cast needed?

like image 415
stefan.s Avatar asked Jan 26 '26 08:01

stefan.s


1 Answers

Numeric literals in C# are int, not byte. Try 0xff.

There is no implicit conversion from int to byte, and the very first statement byte red = 255; is a special case.

A constant expression of type int can be converted to sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant expression is within the range of the destination type.

That doesn't explain why it doesn't convert the constant 255 in the second expression, does it?

It doesn't need to convert 255 in the second expression, because there is an implicit conversion from byte to int. So byte.Parse(redNode.Value) is converted to int. And so (redNode != null) ? byte.Parse(redNode.Value) : 255; is of type int - and because it's not a constant expression, there is no implicit conversion to byte anymore.

You think the error message asks you to do this:

byte red = (redNode != null) ? byte.Parse(redNode.Value) : (byte)255;

but it really was asking you to do that:

byte red = (byte)((redNode != null) ? byte.Parse(redNode.Value) : 255);
like image 200
Peter Avatar answered Jan 27 '26 22:01

Peter