Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

fxcop

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

like image 254
David Robbins Avatar asked Dec 23 '08 01:12

David Robbins


People also ask

In what situation should you use a List instead of an array of T?

Definitely use a List<T> any time you want to add/remove data, since resizing arrays is expensive. If you know the data is fixed length, and you want to micro-optimise for some very specific reason (after benchmarking), then an array may be useful.

Should I use array or List?

Arrays can store data very compactly and are more efficient for storing large amounts of data. Arrays are great for numerical operations; lists cannot directly handle math operations. For example, you can divide each element of an array by the same number with just one line of code.

What namespace is List in C#?

A List is one of the generic collection classes in the "System. Collection. Generic" namespace. There are several generic collection classes in the System.


1 Answers

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.

like image 137
Jon Limjap Avatar answered Oct 22 '22 21:10

Jon Limjap