According to FXCop, List should not be exposed in an API object model. Why is this considered bad practice?
i think you dont want your consumers adding new elements into your return. An API should be clear and complete and if it returns an array, it should return the exact data structure. I dont think it has anything to do with T per say but rather returning a List<> instead of an array [] directly
There are the 2 main reasons:
- List<T> is a rather bloated type with many members not relevant in many scenarios (is too “busy” for public object models).
- The class is unsealed, but not specifically designed to be extended (you cannot override any members)
It's only considered bad practice if you are writing an API that will be used by thousands or millions of developers.
The .NET framework design guidelines are meant for Microsoft's public APIs.
If you have an API that's not being used by a lot of people, you should ignore the warning.
I agree with moose-in-the-jungle here: List<T>
is an unconstrained, bloated object that has a lot of "baggage" in it.
Fortunately the solution is simple: expose IList<T>
instead.
It exposes a barebones interface that has most all of List<T>
's methods (with the exception of things like AddRange()
) and it doesn't constrain you to the specific List<T>
type, which allows your API consumers to use their own custom implementers of IList<T>
.
For even more flexibility, consider exposing some collections to IEnumerable<T>
, when appropriate.
One reason is because List isn't something you can simulate. Even in less-popular libraries, I've seen iterations that used to expose a List object as an IList due to this recommendation, and in later versions decided to not store the data in a list at all (perhaps in a database). Because it was an IList, it wasn't a breaking change to change the implementation underneath the clients and yet keep everyone working.
One of the reason is that user will be able to change the list and owner of the list will not know about this, while in some cases it must do some stuff after adding/removing items to/from the list. Even if it isn't required now it can become a requirement in future. So it is better to add AddXXX / RemoveXXX method to the owner of the class and expose list an an IEnumerable or (which is better in my opinion) expose it as an IList and use ObservableCollection from WindowsBase.