[Proposal] Shorter Alternative To Ternary Operator: Secondary Operator #9128
Unanswered
jwbats
asked this question in
Language Ideas
Replies: 4 comments 24 replies
-
See: #197 |
Beta Was this translation helpful? Give feedback.
3 replies
-
How is this: myObject.Value = (success) ? "New Value" : myObject.Value; Better than this? if (success) myObject.Value = "New Value"; |
Beta Was this translation helpful? Give feedback.
18 replies
-
Personally I think some syntax like this would be very useful as in combination with the spread element ( bool greetTheWorld = ..;
ReadOnlySpan<string> greeting = [
"Hallo",
greetTheWorld && "World"
];
ReadOnlySpan<string> thanks = [ "Thanks", "for", "all", "the", "fish" ];
ReadOnlySpan<string> finalString = [.. greeting, ..(isDolphin && thanks)] |
Beta Was this translation helpful? Give feedback.
3 replies
-
So basically you want “if” as expression rather than a statement. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
We can write if statements, to conditionally assign values, like such:
But some of us would rather eliminate control flow, so we write it using the ternary operator:
The problem is that you are forced to redundantly write "myObject.Value", to ensure this property keeps its old value, in case of !success.
It would be nice if you could write it like this:
Granted, this could also be done using an extension method:
But the resulting call still suffers from redundant property usage:
There is currently no clean, shorthand way of writing a conditional assignment in C#.
It would be nice to have it, IMO.
I guess it would have to be called the "secondary operator", then?
Beta Was this translation helpful? Give feedback.
All reactions