Thursday, November 14, 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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...