[ACCEPTED]-If Then Else Shorthand Won't Work Without Assignment-if-statement

Accepted answer
Score: 18

? : is not "shorthand" for if/else - it 7 is a specific operator (conditional) with 6 specific semantic rules. Those rules mean 5 it can be used only as an expression, not 4 as a statement.

Re the return: if you only 3 want to "return if true", then code it as 2 such:

if(condition) return [result];

Don't try and use a conditional operator 1 as something it is not.

Score: 3

You need to move the return outside the 1 ternary operation.

return boolCondition ? toThisPlace() : 0 ; 
Score: 2

You've got your statement out of order.

Instead 1 of

condition ? return here:return there;

which, as you have found, doesn't compile, do

return condition ? here: there;
Score: 2

No, that's impossible. return is a statement; it 6 cannot be part of an expression, which is 5 what ?:, the ternary operator (not logic control statement), expects 4 in all three of its operands. You'll have 3 to use the usual form. Don't worry though, this 2 is a good thing - it'll make your code more 1 readable in the long run.

Score: 2

The ternary operator ?: is limited in C#. What 1 you could do in this case is:

return condition ? here : there;
Score: 1

You need to write your statement in this 1 way

return condition ? here : there;
Score: 1

The answers are (depending on your C# version 7 and needs):

return condition ? here : there;
return here ?? there; // if you want there when here is null

return boolCondition ? toThisPlace() : default;
return boolCondition ? toThisPlace() : default(int);
return boolCondition ? toThisPlace() : 0;

Now you can assign the result 6 to the underscore '_' variable that will 5 be ignored:

_ = i < a ? i++ : a++;

It's the best I can think of 4 if you really want to avoid if, else, and 3 the brackets that, in some teams, are mandatory 2 to use with every if like this:

if (i < a)

The return 1 in your example will be:

_ = boolCondition = return toThisPlace() : default; // this is horrible, don't do it

More Related questions