3

Why do we need explicit cast in second statement?

bool? a = null; bool b = false; bool c = true;

1.) if(b || c) a = b; else a = null;

2.) a = (b || c)?(Nullable<bool>)b:null;

c161c
  • 31
  • 2
  • The basis of this question has been asked several times. Here is a great answer http://stackoverflow.com/questions/2215745/conditional-operator-cannot-cast-implicitly – jsmith Apr 18 '11 at 19:38

2 Answers2

3

The conditional operator is an expression, thus it needs a return type - also both cases have to have the same return type. In your case, there is no way of determining the return type automatically, thus you need to cast.

Femaref
  • 60,705
  • 7
  • 138
  • 176
  • 1
    They don't have to be the same type, but the second operand has to be implicitly convertible to the compile-time type of the first. – recursive Apr 18 '11 at 19:38
  • 1
    @recursive, or the first implicitly convertible to the second. What you want to avoid is having implicit conversions from each operand to the other, as that also causes ambiguity. – Anthony Pegram Apr 18 '11 at 19:49
0

To add to Femaref, equivalent "if" code will be something like

private static bool? Assign(bool b, bool c)
    {
        if (b || c)
        {
            return b;
        }
        else return null;
    }
...

a = Assign (b,c)

Note the bool? return type. This is what's happening in the conditional operator statement

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • It is not *the* ternary operator, it is the conditional operator. A ternary operator is an operator taking three operands, there can be more than one ;) – Femaref Apr 18 '11 at 19:56
  • In this context the conditional operator is the ternary operator right? – manojlds Apr 18 '11 at 19:57
  • yes, that is true. however, people seem to use ternary operator and conditional operator interchangeably. While true in C#, it is not necessary true in other languages and looking at all operators, not true at all. Just wanted to point that out. – Femaref Apr 18 '11 at 19:59
  • Yup, like in Ruby, there is no the ternary operator, but I was consciously using it here taking the context of the discussion. Anyway edited to change to conditional operator. – manojlds Apr 18 '11 at 20:03