简体   繁体   中英

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
( 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

更好的解决方案是:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM