[ACCEPTED]-If Then Else Shorthand Won't Work Without Assignment-if-statement
? : 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.
You need to move the return outside the 1 ternary operation.
return boolCondition ? toThisPlace() : 0 ;
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;
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.
The ternary operator ?:
is limited in C#. What 1 you could do in this case is:
return condition ? here : there;
You need to write your statement in this 1 way
return condition ? here : there;
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)
{
i++;
}
else
{
a++;
}
The return 1 in your example will be:
_ = boolCondition = return toThisPlace() : default; // this is horrible, don't do it
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.