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

David Robbins picture David Robbins · Dec 23, 2008 · Viewed 18.7k times · Source

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

Answer

Jon Limjap picture Jon Limjap · Dec 23, 2008

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.