Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning IList<T> vs Array in C#?

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.

like image 718
mkelley33 Avatar asked May 02 '09 23:05

mkelley33


People also ask

Does array implement IList?

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.

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 a list or array?

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.

Is IEnumerable list or array?

IEnumerable is read-only and List is not. IEnumerable types have a method to get the next item in the collection.


1 Answers

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.

like image 149
JaredPar Avatar answered Oct 17 '22 15:10

JaredPar