3 ms·
Wow, the ReadOnlyList really does implement all methods of the IList interface. That's just ridiculous, %50 of the methods on the class throw an exception! Why
by gitgud 9y ago
Wow, the ReadOnlyList really does implement all methods of the IList interface. That's just ridiculous, %50 of the methods on the class throw an exception!
Why would the class implement these methods if they aren't even public?
Also, aren't statically typed languages like c# meant to reduce run-time errors by catching them during compilation? Wouldn't throwing exceptions from unimplemented methods from interfaces frequently break this idea?
- contravariant 9y agoIdeally yes you would catch this problem during compile time. However apparently the situations where you need to provide an IList for something that really shouldn't be changed is common enough that they decided to provide this functionality in the ReadOnlyCollection. Now if you read carefully you actually do need to jump through some hoops in order to get an exception. First of all the methods aren't public, you need to explicitly convert the ReadOnlyCollectionto to an IList or ICollection to access them. Secondly the dependency inversion principle requires that any ReadOnlyCollection is stored as an IReadOnlyList or some other appropriate interface, there should be no way to convert it to an IList accidentally. And finally the ReadOnlyCollections seems to be designed for the very specific scenario where you can't solve things using interfaces and need to design a class that supports IList, but throws an exception when it is modified. In all other cases you should use something else.