[Proposal] Allow out ref parameters methods. #9095
Replies: 3 comments 5 replies
-
As low-level unsafe methods, the established practice is to return |
Beta Was this translation helpful? Give feedback.
-
I would also like to note that this would set the groundwork for some version of |
Beta Was this translation helpful? Give feedback.
-
One of the main issues with a
This problem has come up already in the runtime and they chose a different approach. Effectively have a |
Beta Was this translation helpful? Give feedback.
-
Motivation
Many APIs written in C# use some form of a
bool TrySomething(out T value)
pattern, where the return value represents success or failure. This pattern especially ergonomic to use, especially since you can concisely integrate them into if statements or ternaries.However, the moment the success value is a ref, the pattern breaks. The workaround is to return a
ref T
, and anout bool
instead to indicate success or failure.A a contrived example, consider a
ref int TryGetAt(this int[] arr, int index, out bool exists)
extension method implemented on an array.The usage would be:
In fact, the
CollectionMarshal.GetValueRefOrAddDefault()
method does just that.This is quite a lot worse to look at and arguably less readable.
Potential implementation
I believe this feature can be implemented purely through lowering. You can already achieve a similar syntax through wrapping a ref with a ref struct.
With out ref parameters, the code would be simplified like this:
Pros
I also believe this to be a natural extension to the existing
ref
featuresCons
T**
. Anout
is already a form of aref
, after all.ref
Beta Was this translation helpful? Give feedback.
All reactions