There are several similar questions already on SO, but not one of the ones I found touches on this topic, so here it is ...
I understand that you should always try to return the interface over a specific class. I won’t go for the reasons behind this, there are a lot of things about SO about this already.
However, in the case of IReadOnlyCollectionvs a, ReadOnlyCollectionI am not sure whether this rule should be followed.
An IReadOnlyCollectioncan be easily distinguished in List, which ... well ... breaks down the aspect ReadOnlyinto contract promises.
ReadOnlyCollectionhowever cannot be added to List, but that means returning a specific class.
Ultimately, does it really matter? It seems to me that in most cases an object is ReadOnly*/IReadOnly*returned only by a returned method or a read-only property.
Thus, even if the user decides to pass it on to something else (in the case of the object IReadOnly*) or use LINQ to create some collection from it (in the case of the object ReadOnly*), there really is no way for the class displaying the object ReadOnly*/IReadOnly*to accept it back.
So, what is the recommendation here, return an interface IReadOnly*or a specific instance of a class ReadOnly*?
source
share