Does .Net provide a pure IReadOnlyList\<T\> implementation? #115594
Replies: 3 comments 2 replies
-
This is the de-factor standard since the read-only interfaces came much later in .NET. Both arrays and
The common practice for xaml collections is to use |
Beta Was this translation helpful? Give feedback.
-
I agree that ObservableCollection is a decent general-purpose class but it doesn't address ordered or indexed set cases. In practice, I can find no good .Net solution for an observable set that is ordered or indexed because there doesn't appear to be one that allows overriding key methods. As a result, I end up creating a base class that implements IReadOnlyCollection<T>, INotifyCollectionChanged, INotifyPropertyChanged with associated virtual protected methods. Maui's CollectionView currently prevents using a pure read-only observable collection and I'm hoping to get this addressed there and avoid all the negative testing required to provide an IList implementation. |
Beta Was this translation helpful? Give feedback.
-
On the surface, yes but, in practice, both ICollection and IList have a second key, the item itself as expressed through ICollection.Contains and IList.IndexOf both of which are O(n) operations in the two collection classes. At this point, the question is moot, but I still think the pattern should have been IReadOnly -> IReadWrite and avoid all the unnecessary NotSupportException stubs. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Alternatively: Why isn't ReadOnlyCollection<T> a pure read-only collection?
I've seen recommendations in various places that ReadOnlyCollection should be used as the implementation class for IReadOnly|T> but this seems like a poor choice since it implements IList and IList<T> with a bunch of stub methods that simply throw NotSupportedException.
From a design standpoint, I feel this is flawed. From a practical standpoint, it can end up producing unintended requirements.
This has bugged me for a while but I recently hit a case where it caused an issue so I figured I'd ask.
A case in point is Maui's CollectionView. While it supports INotifyCollectionChanged, it fails to do so if the ItemsSource does not also implement IList or IList<T>.
The result is I either must use ReadOnlyCollection<T> or implement the list contract with all the appropriate stub methods.
In my case, I implement INotifyCollectionChanged because the collection will change or be reordered and IReadOnlyList because it cannot be publicly updated. As a result, I end up doing both, provide a List<T> to the base class and override List.Contains for custom ordering.
Beta Was this translation helpful? Give feedback.
All reactions