6

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.

svick
  • 236,525
  • 50
  • 385
  • 514
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • 7
    Don't be clever; clever code is bad code. You're not writing a detective novel or a book of logic puzzles here; code is valuable when it is *correct* and *easy to understand*. More specifically: use *expressions* for *computations* and *statements* for *control flow*. You are trying to use an expression for control flow and that is working *against* the design of the tool, not with it. – Eric Lippert Feb 21 '12 at 00:16
  • 7
    @EricLippert - I am working on an action/adventure novel written entirely in c#, predicated on the terms that all code be clever. Page 1: `IScene OpeningScene = new PanoramicScene(); OpeningScene.panToAction();` It will be called "I c# in the dark" and feature werewolves. But back to the point, thanks for the tips. I will keep that in mind. – Travis J Feb 21 '12 at 00:28
  • I love this syntax. It's much cleaner than lot of empty lines of opening and closing brackets. I am missing this too in C#. As well as I am missing some operator for chaining lambdas. It is much more natural to write MyFunction() => DoA() & DoB(); or MyFunction() => IsA ? DoA() : DoB(); To achieve such code I sometimes create methods to unnecessary return bools so I can chain them, but but this just moves requirement to do it level below. The same goes for switch statement and other pieces of code. C# just doesn't treat functions as first level citizens :( – Adas Lesniak Jan 25 '23 at 19:16

8 Answers8

18

? : 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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Technically it is not. It generates less instructions and allocates less on stack, so it's optimized shorthand. From user perspective can you tell any difference? Logical difference where one code would be valid and other not? Skipping that ?: can't be applied to expressions and aesthetics/clarity aspects. – Adas Lesniak Jan 25 '23 at 19:29
  • @AdasLesniak that is a bold statement and would require specific examples to discuss; there *is* perhaps a difference in priority between which branch it anticipates being taken; compare the IL for `Foo` and `Bar` here: https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBLANgHwAEBGJAAhIAYyAxCCACmwDsMzsBKAWACgBvXmSEUA7OzIAeALxkUAJjIB+MgCIAhsDAqyIMgHEYGAMoQAtjCMYoLAOYMOAbl4BfXiXJUyAITVQmrdm5+QWFsADMyJkkZeQ5RVQ0tJx5heINjMwsrW3tk1x53CmJqdJNzS2tmOzipAD5VABMYMJUHIA=== – Marc Gravell Jan 26 '23 at 12:54
3

You need to move the return outside the ternary operation.

return boolCondition ? toThisPlace() : 0 ; 
Bruno Silva
  • 3,077
  • 18
  • 20
  • If I do that, won't it return 0 if the condition is false? I only want to return if true. – Travis J Feb 21 '12 at 00:11
  • 2
    In that case you have to use `if`. `if (boolCondition) return toThisPlace();`. The ternary operator is not a replacement for if-else. – Bruno Silva Feb 21 '12 at 00:14
3

You've got your statement out of order.

Instead of

condition ? return here:return there;

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

return condition ? here: there;
Loren Pechtel
  • 8,945
  • 3
  • 33
  • 45
2

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

Ry-
  • 218,210
  • 55
  • 464
  • 476
2

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

return condition ? here : there;
John Pick
  • 5,562
  • 31
  • 31
1

The answers are (depending on your C# version 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 to the underscore '_' variable that will be ignored:

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

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

if (i < a)
{
    i++;
}
else
{
    a++;
}

The return in your example will be:

_ = boolCondition = return toThisPlace() : default; // this is horrible, don't do it
Dodger
  • 342
  • 3
  • 9
1

You need to write your statement in this way

return condition ? here : there;
Steve
  • 213,761
  • 22
  • 232
  • 286
-3

your code is ok the only problem is that you're reading the i variable on the condition and at the same moment you're trying to change the value of the variable

Asmodeo
  • 43
  • 3