(myCondition!="true")
? output("false"); doSomethingElse();
: output("true")
Why does the IDE say at the double-dot "Expected semicolon" ?
The conditional operator isn't a "short if form"... it's an operator, which evaluates either the third operand or the second operand based on the evaluation of the first operand. The result of the whole expression is the result of whichever operand was evaluated (out of the 2nd/3rd), converted to the result type where necessary (either the 2nd and 3rd operands have to be of the same type, or there must be an implicit conversion of one to the other).
You can't use it as an individual statement, and you certainly can't have multiple statements as the operands. Note that it must evaluate to a value - if Output
and DoSomethingElse
are void
methods, that's another reason why you couldn't use the conditional operator.
Just don't do it. When you want the execution model of an if
statement, use an if
statement.
// I generally try to make conditions positive where possible. It's easier to read IMO.
if (myCondition == "true")
{
Output("true");
}
else
{
Output("false");
DoSomethingElse();
}
See more on this question at Stackoverflow