Thursday, 19 September 2019

c# - Returning 'IList' vs 'ICollection' vs 'Collection'



I am confused about which collection type that I should return from my public API methods and properties.



The collections that I have in mind are IList, ICollection and Collection.



Is returning one of these types always preferred over the others, or does it depend on the specific situation?


Answer



Generally you should return a type that is as general as possible, i.e. one that knows just enough of the returned data that the consumer needs to use. That way you have greater freedom to change the implementation of the API, without breaking the code that is using it.




Consider also the IEnumerable interface as return type. If the result is only going to be iterated, the consumer doesn't need more than that.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...