1

Possible Duplicate:
Why is this code invalid in C#?
Conditional operator cannot cast implicitly?

If I do the following:

bool someBool = false;
uint value = 0;

These are fine:

value = (someBool) ? 0 : (uint)1;
value = (someBool) ? (uint)0 : 1;

But this is not:

value = (someBool) ? 0 : 1;

Why can I not use the last one when I can easily say:

value = 0;
value = 1;

How is the type of the ternary operator determined?

Community
  • 1
  • 1
NominSim
  • 8,447
  • 3
  • 28
  • 38

3 Answers3

4

You must cast it to uint so the compiler will know. Both 0 and 1 could be a uint or an int.

Here is the language specification (which can be downloaded from MSDN here):

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

If X and Y are the same type, then this is the type of the conditional expression.

Otherwise, if an implicit conversion exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

Otherwise, if an implicit conversion exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

Otherwise, no expression type can be determined, and a compile-time error occurs.

Bryan Crosby
  • 6,486
  • 3
  • 36
  • 55
1

If you do not cast any of the numbers to uint, the compiler is going to assume that the result of the ternary operator is an int, which cannot be implicitly converted to uint.

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
1

My short summary :

  var x = c ? a : b;

The compiler will try if b is convertible to the type of a, otherwise if a is convertible to the type of b. When neither is possible there is an error.

But in

 uint value = (someBool) ? 0 : 1;

the ternary operator simply return int (both a and b are ints here).

The variable on the left side of the assignment is not considered when determining the type.

H H
  • 263,252
  • 30
  • 330
  • 514