Nullable ref Value property #73117
Answered
by
PathogenDavid
emceelovin
asked this question in
General
-
FEATURE_NAME
SummaryTo avoid CS1612's, unnecessary copies, and because it just makes sense, Nullable.Value should be updated to return by reference. Detailed designpublic struct NestedValueType
{
public string StringProp { get; set; }
}
public struct Nullable<T>
{
// public ref T Value => ref _value
public T Value => _value;
public ref T ByRefValue => ref _value;
T _value;
}
public void Serialize(ref Nullable<NestedValueType> obj)
{
/*
* CS1612. StringProperty is returned as a copy as it's the return value of the internal getter and not a variable.
*/
obj.Value.StringProp = reader.ReadString();
/*
* Bingo. Zero copies of any of the value type's anywhere. The desirable should-be outcome.
*/
obj.ByRefValue.StringProp = string.Empty;
/*
* This shouldn't break anything
* either. If you were to try and assign the ref read property to a non reference, it would just be copied like the typical
* non by ref property
*/
NestedValueType copy = obj.ByRefValue;
} DrawbacksYou tell me? Alternatives// I emitted the IL version of this with DynamicMethod and ILGenerator
public ref T GetNullableValueByRef<T>(ref Nullable<T> nullable)
{
return ref nullable._value;
} |
Beta Was this translation helpful? Give feedback.
Answered by
PathogenDavid
Jul 30, 2022
Replies: 2 comments 1 reply
-
Moving to runtime. This is not a language decision. |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
emceelovin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nullable.GetValueRefOrDefaultRef<T>
has been accepted to .NET 7 and is already available in .NET 7 previews.(See PR #64677 and API proposal #1534)