Why is it considered bad to expose List<T>? [duplicate]

According to FXCop, List should not be exposed in an API object model. Why is this considered bad practice?


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.


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 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