According to FXCop, List should not be exposed in an API object model. Why is this considered bad practice?
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.
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.
A List is one of the generic collection classes in the "System. Collection. Generic" namespace. There are several generic collection classes in the System.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With