Replies: 2 comments 8 replies
-
It should be more risky than If you are referencing a "list" that won't change after, |
Beta Was this translation helpful? Give feedback.
-
This has been suggested repeatedly before, see #90141, #101914 and #105179. While I too think this would be a useful addition, @stephentoub and @tannergooding disagree, citing the following reasons:
But it doesn't matter all that much. .NET 9 allows public static Memory<T> AsMemory<T>(this List<T> _list)
{
#if NET9_0_OR_GREATER
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_items")]
extern static ref T[] GetListItems(List<T> list);
var items = GetListItems(_list);
#else
var items = (T[])_list.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(_list)!;
#endif
return new Memory<T>(items, 0, _list.Count);
} |
Beta Was this translation helpful? Give feedback.
-
Hello,
in the software I'm working on we use
ReadOnlyMemory<T>
to pass around collections of readonly structs to some async methods to take advantage of ref enumerators and accessors.Very often those
ReadOnlyMemory<T>
are created starting fromList<T>
and getting aT[]
out of it uaing theToArray
method. Since this step allocates an unecessary array each time, I was looking for some method to get aMemory<T>
(orReadOnlyMemory<T>
) from theList<T>
itself the same wayCollectionsMarshal.AsSpan
does forSpan<T>
? I'd like to avoid creating an overload taking aList<T>
for each async method...Has
CollectionsMarshal.AsMemory
ever been considered? Is there any downside having such method?Also, is taking a
ReadOnlyMemory<T>
instead ofIEnumerable<T>
orIReadOnlyList<T>
really worth the additional allocation of aT[]
?Beta Was this translation helpful? Give feedback.
All reactions