[Discussion] Conditional Returns #325
Replies: 5 comments 1 reply
-
The following is already legal C# syntax: return (foo) => bar; Even if you eliminated that ambiguity I don't see much utility in this proposal. All it seems to do is conflate conditions with returning values. In my opinion it doesn't improve readability of the code and the keystroke savings is minimal, at best. |
Beta Was this translation helpful? Give feedback.
-
This syntax is confusing and I think it accomplishes exactly the opposite of your stated goal of putting intent first. |
Beta Was this translation helpful? Give feedback.
-
I was once propose syntax |
Beta Was this translation helpful? Give feedback.
-
Another use case for the public (bool success, string result, object details) Foo(Item inItem) =>
(CheckItem(inItem) is var result && result, result ? DoWork() : default) match (
case (false, _) : (false, "CheckFail", null),
case (_, bar) when !bar.success: (
bar.success,
Convert.Result( bar.ActivityResult ),
thing.Where(s=>s.Details == bar.detailsKey)),
case (_, bar): (
...
...
...)
); (ignored the "default" as that's unreachable) |
Beta Was this translation helpful? Give feedback.
-
I see some issues and discussions and they seme to point to this one as the "original". if(argument < 0 )
{
return;
} I think it would be nice to be able to write it like this: return if argument < 0; This is different from: if (argument < 0) return; Because:
We already have the same improvement on the basis of ArgumentNullException. if(argument is null)
{
throw new ArgumentNullExcetpion();
} NOW: ArgumentNullException.ThrowIfNull(argument); So it would be concise - Throw If Null, Return If Null |
Beta Was this translation helpful? Give feedback.
-
I was playing around where I was returning an early check result and didn't like having the
return
in the middle of the line. The intent was more important than the condition. I thought a conditional return would be nice. Then I though about the common practice of having a single return at the bottom of a method and wrap things in cases and ifs to support this. It adds a lot of wordiness. Even with multiple returns, sometimes these get wrapped in cases. A potentially cleaner coding style can be used if we had conditional returns. In the simplest form it just allows reversing the keyword and predicate:This can eliminate a lot of if's and cases
You have to be aware of the order of things, but with the changes to
switch
with pattern matching, you have to now anyway.Beta Was this translation helpful? Give feedback.
All reactions