3

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?

stefan.s
  • 3,489
  • 2
  • 30
  • 44
  • because both if else should return same type of instance – Ehsan Sajjad May 30 '16 at 12:23
  • There is no implicit cast from int to byte, but there is an explicit one. It is named "explicit" for a reason - you need to apply it, well, explicitly :) – Evk May 30 '16 at 12:25

1 Answers1

3

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);
Peter
  • 5,608
  • 1
  • 24
  • 43