EDIT: The original question used an int?
. It's now been fixed.
That code won't even compile, so yes, I'd say it's too cryptic.
Typos aside, the fact that you posted it without easily spotting that there's a problem (you're trying to use a bool
on the RHS of the ??, when the LHS is an int?
) suggests it's not a good idea even when you get it right.
I'd need to see a real-world example, but I think I'd usually split this into one statement using the null coalescing operator, and then another using the conditional operator. Another option is to use the behaviour of nullable types in relation to operators... but again, that's reasonably obscure. (I've just had to remind myself exactly what that behaviour is!)
I like the null coalescing operator in general, but I think combining it with the conditional operator just makes it a little bit to obscure. I think I'd probably accept it in a case where there was a significant benefit to it being a single expression (e.g. for initialization where the alternative is introducing an extra method) but in general I'd prefer to split it into two statements.
EDIT: One alternative in this particular case is to just compare against "true" - which looks redundant, but isn't in the case of bool?
:
result = (testBool == true) ? "Yes" : "No";
The brackets aren't necessary, of course, but add clarity IMO.
I think this is simpler: the result is only "Yes" if testBool
is actually true; otherwise it's "No". If you wanted to "default" to Yes, you'd write:
result = (testBool == false) ? "No" : "Yes";