Question

The new read-only interfaces in .NET 4.5 such as IReadOnlyCollection<T> and IReadOnlyDictionary<TKey,TValue> are very useful, especially since they have been implemented on common BCL types such as Collection<T>, List<T> and Dictionary<TKey,TValue>.

However, HashSet<T> and SortedSet<T> haven't been upgraded to implement IReadOnlyCollection<T>, and I can't see the logic behind this decision since those classes match the interface without any modification or breaking change. Was it just overlooked by the BCL team, or is there something I'm missing here?

(This is especially annoying since there are no built-in ways to wrap a set inside a IReadOnlyCollection<T>. Indeed, ReadOnlyCollection<T> wraps IList<T> and not ICollection<T>. I know writing my own wrapper is trivial.)

Was it helpful?

Solution 2

The most likely reason the IReadOnlyXxx interfaces where added in 4.5 was because they were required to make .NET collections usable in WinRT projects (Store and Phone apps). Necessary to properly map the collection to WinRT's IVectorView<> and IMapView<> interfaces. This is done automagically by the language projection built into the CLR. With the clincher that WinRT doesn't have the equivalent of an ISet<> interface so there just wasn't any need to change HashSet<>.


Update: the asymmetry was resolved in .NET 4.5.1, no doubt thanks to plenty of customer feedback :), HashSet<> now also implements IReadOnlyCollection<>

OTHER TIPS

Update 2015: Fixed in .NET 4.6

Read-only interfaces are implemented on collection types HashSet, LinkedList, Queue, SortedDictionary, SortedList, SortedSet, and Stack. [944715]

https://dotnet2015.blob.core.windows.net/changes/dotnet46-changes.txt

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top