I was recently asking someone why he preferred to return a strongly-typed array over an IList. I had always thought that programming against an interface was the most flexible and best way program when faced with a project having a long life. So it struck me as odd when he replied:
We typically prefer immutable types over mutable ones. Arrays are immutable. IList is not.
I'm not entirely sure I understand this statement. Can anyone help clarify this?
Thanks for any help you guys can provide.
Definition of IList interface is "Represents a non-generic collection of objects that can be individually accessed by index.". Array completely satisfies this definition, so must implement the interface.
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.
IEnumerable is read-only and List is not. IEnumerable types have a method to get the next item in the collection.
Whoever "he" is, is in 100% wrong on the topic. Arrays are a very much mutable. This is in fact one of the reasons not to return an array. There is no way to prevent a caller from changing the elements of an array to whatever they please.
The only way in which an Arrray is immutable is in it's length. Once an array is allocated, it's length cannot be changed. Even APIs such as Array.Resize don't actually resize the array, they just allocate a new one, copy the contents and return the new array (by reference in this case).
I do agree however that there are many cases in which it is better to return immutable data. The primary one is that it allows you to return a reference to an internal collection of a class without doing a complete copy and at the same time preventing the caller from messing with your internal state. Most mutable collections cannot make such guarantees.
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