Skip to main content
2 of 3
added 659 characters in body
JacquesB
  • 62.4k
  • 21
  • 137
  • 190

The array interface has several problems. Firstly, it is not as type safe as other collection types. Consider this example:

 object[] x = new string[]{"a", "b", "c"}; x[2] = new DateTime(); 

This will compile correctly but give you a run-time exception. Usually you would expect code to be type safe as long as there is no explicit casting, but arrays have a specific weakness which is not shared by other types. If you had used some of the other collection types or interfaces, the error would have been detected at compile time (for example you can't assign a List<string> to a variable of type List<object>).

Secondly, arrays are a weird combination of mutable and immutable: You can replace elements, but you cant add or remove elements. This is almost never a useful contract. Either you want a collection to be fully immutable or you want it to be fully mutable.

You usually want one of:

  • IEnumerable<T> - immutable, sequential access
  • IReadOnlyList<T> - immutable, random access to elements
  • IList<T> - mutable

Arrays are often fine as the implementation exposed as a IEnumerable<T> or IReadOnlyList<T> since those interfaces protect against the type-safety issue. But there is an additional issue with exposing an array as IList<T>: Arrays actually implement this interface, but will throw a runtime exception if you attempt to add or remove elements. So again it gives you run-time errors instead of compile-time errors.

In short, arrays are not as type safe as other collection types.

JacquesB
  • 62.4k
  • 21
  • 137
  • 190