[Proposal] Conditional return statements #9283
Replies: 1 comment 8 replies
-
Idiomatic C# would be: if (condition) return expr; |
Beta Was this translation helpful? Give feedback.
8 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.
Uh oh!
There was an error while loading. Please reload this page.
-
I have come to grow very fond of the concise, unindented code block that you can put at the start of a method body for safeguards using
ArgumentNullException.ThrowIfNull(arg)
etc.However, the "neatness" of these blocks is disturbed when you want to return rather than throw:
You can try to force it into a single line, like so:
but that wouldn't persist in any codebase I have worked on so far, since they all enforce brackets and new lines for
if
statements. (Maybe people would agree to havereturn
andthrow
statements as an exception, but since you cannot configure that, those neat one-liners will be expanded upon next code cleanup. It gets even worse if the style also enforces an empty line after a closing}
.)Therefore, I would like to suggest conditional returns:
The part behind the
if
is any expression valid for anif
statement, so you could also do stuff likewhich actually yields natural English language when read aloud, and is IMHO slightly prettier than one-liners (if they persisted)
and a lot more concise than
Bonus thoughts:
(
)
brackets for the conditional expression, since there is no code betweenif
and;
that's not part of it.when
instead ofif
because that would look similar tocatch x when y
, but I thinkx when y
meansy
is a filter forx
, which it wouldn't be inreturn x when y
.return if <expr>;
statement forvoid
methods.P. S.: Since I suspect the syntax highlighting isn't going to work on my proposal, here's what the code would look like when highlighted:
Beta Was this translation helpful? Give feedback.
All reactions