24

When I compile my C# project in MonoDevelop, I get the following error:

Type of conditional expression cannot be determined as 'byte' and 'int' convert implicitly to each other

Code Snippet:

byte oldType = type;
type = bindings[type];
//Ignores updating blocks that are the same and send block only to the player
if (b == (byte)((painting || action == 1) ? type : 0))
{
    if (painting || oldType != type) { SendBlockchange(x, y, z, b); } return;
}

This is the line that is highlighted in the error:

if (b == (byte)((painting || action == 1) ? type : 0))

Help is greatly appreciated!

Jakir00
  • 2,023
  • 4
  • 20
  • 32

2 Answers2

32

The conditional operator is an expression and thus needs a return type, and both paths have to have the same return type.

(painting || action == 1) ? type : (byte)0
Femaref
  • 60,705
  • 7
  • 138
  • 176
  • 2
    How about in the case where the parameter is expected to be any type such as `String.Format("value: {0}", (value == null) ? : "null" : value)` where value is of type `int?`? – mr5 May 03 '17 at 08:32
5

There is no implicit conversion between byte and int, so you need to specify one in the results of the ternary operator:

? type : (byte)0

Both return types on this operator need to either be the same or have an implicit conversion defined in order to work.

From MSDN ?: Operator:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

Oded
  • 489,969
  • 99
  • 883
  • 1,009