Single statement returns with out parameters #7191
Replies: 3 comments 3 replies
-
pos = -1; return false; is already legal and shorter than: return false with pos = -1; |
Beta Was this translation helpful? Give feedback.
-
A tuple can be used to avoid the need for static (bool needed, int pos) NeedsEscaping(string? input)
{
if (string.IsNullOrEmpty(input)) return (false, -1);
if (input.StartsWith(' ')) return (true, 0);
for (var i = 0; i < input.Length; i++)
{
if (input[i] is '"' or '\'' or '\\') return (true, i);
}
if (input.EndsWith(' ')) return (true, input.Length - 1);
return (false, -1);
} and that can be matched in much the same way: if (NeedsEscaping(someString) is (true, var pos))
{
// do something with pos...
} Out parameters really aren't needed anymore as we have NRTs, records, tuples and hopefully soon unions that all handle multiple return values far better. Further, Microsoft's own quality analyzer rule, CA1021: Avoid out parameters discourages the use of out parameters. Therefore the case for extending syntax around out parameters really feels far from compelling to me. |
Beta Was this translation helpful? Give feedback.
-
Closing it as @DavidArno somewhat explained why this will never happen
|
Beta Was this translation helpful? Give feedback.
-
Not sure if this was proposed before, I couldn't find it. When a method has a return type and
out
parameters, it gets verbose to populate them. Consider this made up function that determines if a string needs escaping, and returns the first escaped character index if so:With the proposed new syntax, return statements can include assignments for the out parameters:
When there are multiple out parameters, they can be assigned in a single statement, separating assignments with a comma:
Which would be lowered into:
Beta Was this translation helpful? Give feedback.
All reactions