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;
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;
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.
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