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.
? : 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.
You need to move the return outside the ternary operation.
return boolCondition ? toThisPlace() : 0 ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With