Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Then Else Shorthand Won't Work Without Assignment

In C#, I am trying to shorten some of my return code. What I want to do is something like

condition ? return here:return there;

or

condition ?? return here;

I am having some issues though, the compiler says the expression is not valid. Here is an example:

        int i = 1;
        int a = 2;
        i < a ? i++ : a++;

This is not valid. However,

        int i = 1;
        int a = 2;
        int s = i < a ? i++ : a++;

is valid. Must there be assignment to use this shorthand notation? The only way I can think of using this at the moment is:

int acceptReturn = boolCondition ? return toThisPlace() : 0 ;

I would really like that line of code to look more like:

boolCondition ? return toThisPlace():;

Which is not valid but is what I am after.

like image 802
Travis J Avatar asked Nov 28 '22 22:11

Travis J


2 Answers

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

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

if(condition) return [result];

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

like image 154
Marc Gravell Avatar answered Dec 15 '22 06:12

Marc Gravell


You need to move the return outside the ternary operation.

return boolCondition ? toThisPlace() : 0 ; 
like image 36
Bruno Silva Avatar answered Dec 15 '22 07:12

Bruno Silva