开发者

if-else shortcut surprise

i was totally surprised that the 3rd solution doesn't work (Compiler says: ; is missing).

bool isFoobar = true;

isFoobar == true ? isFoobar = false : isFoobar = true; // [1] works
开发者_如何学JAVA( isFoobar ? isFoobar = false : isFoobar = true ); // [2] works
isFoobar ? isFoobar = false : isFoobar = true; // [3] failed

Ehm, why does the last one not work?


None of those is correct. I get compiler errors with them all.

The correct syntax is:

isFoobar = isFoobar ? false : true;

update

The errors I get with your statements are:

1 & 2:

Only assignment, call, increment, decrement, and new object expressions can be used as a statement

3:

Invalid expression term ':'

; expected

; expected


A better solution is:

isFoobar = !isFoobar;


When I try the code, neither of those work. You can't use an expression like that as a statement.

If you use the expressions as expressions, all three work:

bool isFoobar = true;
bool x;

x = isFoobar == true ? isFoobar = false : isFoobar = true;
x = ( isFoobar ? isFoobar = false : isFoobar = true );
x = isFoobar ? isFoobar = false : isFoobar = true;

If you only want to use it as a shortcut for if, and don't want to use the result, you are using it the wrong way. The conditional operator should be used for expressions, not instead of an if statement.


under .net 3.5 this work and compile

        bool isFoobar = true;

        var a = isFoobar == true ? isFoobar = false : isFoobar = true; // [1] works
        var b = ( isFoobar ? isFoobar = false : isFoobar = true ); // [2] works
        var c = isFoobar ? isFoobar = false : isFoobar = true; // [3] works

a, b and c are type boolean


You are using it the wrong way. The ternary operator is there to assign a variable based upon a predicate, not to execute code in the two cases.

  var obj = predicate ? true_case : false_case; //if predicate is true, true_case will be assigned to obj.


You are mistaken - none of them compile. Try commenting out the third line and see what happens. The true/false part of the ternary statement needs to return a value, which you are not doing.


If statement is only like below:

isFoobar ? isFoobar = false : isFoobar = true;

It gives same error as in the question,

If statement is like:

isFoobar ? (isFoobar = false) : (isFoobar = true);

Error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜