From #88093 (comment):
We should revisit this.
|
/// The reason we don't copy anything other than for well-known types is that a malicious interface |
|
/// implementation of <see cref="ICollection{T}"/> could hold on to the array when its <see cref="ICollection{T}.CopyTo"/> |
|
/// method is called. If the array it holds onto underlies an <see cref="ImmutableArray{T}"/>, it could violate |
|
/// immutability by modifying the array. |
That logic, while well-meaning, isn't worth making the implementations slower. If code wants to get at the underlying array of an ImmutableArray, there are easier ways, including a now fully supported public API.
The comment that triggered the conversation #88093 (comment):
The custom ToArray implementation is slower, because it uses CopyTo only for collections that implement IList<T>, while both KeyCollection and ValueCollection don't. They do implement ICollection<T> which is used by LINQ.
|
if (!sequence.TryCopyTo(array, 0)) |
|
{ |
|
int i = 0; |
|
foreach (T item in sequence) |
|
{ |
|
Requires.Argument(i < count); |
|
array[i++] = item; |
|
if (sequence is IList<T>) |
|
public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable |
|
public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable |
cc @stephentoub
From #88093 (comment):
The comment that triggered the conversation #88093 (comment):
runtime/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs
Lines 158 to 164 in c06d77a
runtime/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs
Line 106 in c06d77a
runtime/src/libraries/System.Collections/ref/System.Collections.cs
Line 504 in c06d77a
runtime/src/libraries/System.Collections/ref/System.Collections.cs
Line 532 in c06d77a
cc @stephentoub