Look at the specification of the ReadOnlyCollection class, it does implements the IList interface, right.
The IList interface have Add/Update/Read methods, which we call it pre-conditions of the interface. Anywhere in my application if I have an IList I should be able to do all this kind of operations.
But what about if I return a ReadOnlyCollection somewhere in my code and try to call the .Add(...) method? It throws a NotSupportedException. Do you think this is a good example of a bad design? Additionally, is this class breaking the Liskov Substitution Principle?
Why did Microsoft implemented this way? Should it be easier (and better) to make this ReadOnlyCollection implements only the IEnumerable interface (which is, by the way, already readonly)?
Yes, it is bad design indeed. The collection interfaces are lacking in .NET: there are no read-only interfaces.
Did you know that string[]
implements IList<string>
(and ditto for other types)? This has the same problem: you would expect that you can call Add
and Remove
on the interface, but it would throw.
Unfortunately, this cannot be changed anymore without breaking backwards compatibility, but I agree with you that it is very bad design. A better design would have seen separate interfaces for the read-only capabilities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With