Open ghost opened 1 year ago
Tagging subscribers to this area: @dotnet/area-system-collections See info in area-owners.md if you want to be subscribed.
Author: | cakescience |
---|---|
Assignees: | - |
Labels: | `api-suggestion`, `area-System.Collections` |
Milestone: | - |
- Call
IEnumerable.ToList<TSource>
thenList<T>.AsReadOnly
but this will allocate a newList<T>
.
No. This is semantically different, since it copies the content of the collection, instead of creating a read-only view.
ReadOnlyCollection<T>
is in fact an "readonly list" wrapper. However, HashSet<T>
implements IReadOnlyCollection<T>
directly and there's no need to create a wrapper. You can't convert arbitrary ICollection<T>
to IReadOnlyCollection<T>
though, but can you give real-world business example? ICollection<T>
itself is much less popular than IList<T>
.
I'm currently using
ICollection<T>
and there's no easy way to convert it toIReadOnlyCollection<T>
.
Yes, this is a historical pain since the read-only interfaces came later.
Is the collection implemented by yourself or the BCL? You can easily add IReadOnlyCollection<T>
to your collections. All the BCL collections should have implemented it. If not, we should probably add it.
Are you passing collections in ICollection<T>
instead of its concrete type? This is a valid scenario. But if you can make sure the collection implements IReadOnlyCollection<T>
, you can do a cast when passing to the third-party library as a workaround.
Is your recommendation to switch from
ICollection<T>
toIList<T>
?
IReadOnlyCollection<T>
gives literally little capacity (count only) thus it's not popular. Is there any reason to not use IList<T>
?
Following the pattern of other read-only collections, shouldn't this expose a new collection type akin to ReadOnlyCollection<T>
(that is actually a read-only list)?
shouldn't this expose a new collection type akin to
ReadOnlyCollection<T>
(that is actually a read-only list)?
This is the expected approach, however the name is already taken.
Background and motivation
Like
List<T>.AsReadOnly
, I'd like to propose the same forICollection<T>
. If I'm not mistaken, currently to convert an instance ofICollection<T>
toIReadOnlyCollection<T>
, we need either:IEnumerable.ToList<TSource>
thenList<T>.AsReadOnly
but this will allocate a newList<T>
.Create a custom extension method
AsReadOnly
onICollection<T>
like:API Proposal
API Usage
Alternative Designs
No response
Risks
Nothing I can see.