-
Notifications
You must be signed in to change notification settings - Fork 4.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add ref accessors for List<T> #54999
Comments
Tagging subscribers to this area: @eiriktsarpalis Issue DetailsBackground and MotivationAdd ref accessors for Motivation Updating struct LargeStruct
{
// Other members...
public int MyInt { get; set; }
// Other members...
}
LargeStruct value= list[index]; // struct copy
value.MyInt++;
list[index] = value; // another struct copy Proposed APInamespace System.Runtime.InteropServices
{
public static class CollectionsMarshal
{
/// <summary>
/// Gets a reference to the value at the given <paramref name="index"/>.
/// </summary>
public static ref T GetValueRef<T>(List<T> list, int index);
}
} Usage Examplesref LargeStruct value = ref CollectionsMarshal.GetValueRef(list, index); // avoid struct copy
value.MyInt++; Alternative DesignsIt can also be resolved using // List<T> use AsSpan
ref var listRef = ref CollectionsMarshal.AsSpan(list)[index];
// Dictionary<TKey, TValue> use ref accessor
ref var dictRef = ref CollectionsMarshal.GetValueRef(dictionary, key).MyInt++; Risks
|
I think The list and dictionary methods lives in the same class |
Both great points. Unlike Dictionary I don't think there is much benefit in exposing ref accessors for List. I will close this issue, but we can always revisit should we discover a compelling reason to include it. |
Thanks for reviewing! |
Background and Motivation
Add ref accessors for
List<T>
same asDictionary<TKey, TValue>
. #27062.Motivation
Updating
struct
causes struct copies. It may be expensive.Proposed API
Usage Examples
Alternative Designs
It can also be resolved using
CollectionsMarshal.AsSpan
, but it doesn't correspond to API ofDictionary<TKey, TValue>
.I think this is non-intuitive.
Risks
The text was updated successfully, but these errors were encountered: