You need arrays to manage your collection of mutable structs, of course, and what would we do without those.
struct EvilMutableStruct { public double X; } // don't do this
EvilMutableStruct[] myArray = new EvilMutableStruct[1];
myArray[0] = new EvilMutableStruct()
myArray[0].X = 1; // works, this modifies the original struct
List<EvilMutableStruct> myList = new List<EvilMutableStruct>();
myList.Add(new EvilMutableStruct());
myList[0].X = 1; // does not work, the List will return a *copy* of the struct
(note that there may be some cases where an array of mutable struct is desireable, but usually this differing behavior of mutable structs within arrays versus other collections is a source of errors that should be avoided)
More seriously, you need an array if you want to pass an element by reference. i.e.
Interlocked.Increment(ref myArray[i]); // works
Interlocked.Increment(ref myList[i]); // does not work, you can't pass a property by reference
That can be useful for lock-free threadsafe code.
You need an array if you quickly and efficiently want to initialize your fixed-size collection with the default value.
double[] myArray = new double[1000]; // contains 1000 '0' values
// without further initialisation
List<double> myList = new List<double>(1000) // internally contains 1000 '0' values,
// since List uses an array as backing storage,
// but you cannot access those
for (int i =0; i<1000; i++) myList.Add(0); // slow and inelegant
(note that it would be possible to implement a constructor for List that does the same, it's just that c# does not offer this feature)
you need an array if you want to efficiently copy parts of the collection
Array.Copy(array1, index1, array2, index2, length) // can't get any faster than this
double[,] array2d = new double[10,100];
double[] arraySerialized = new double[10*100];
Array.Copy(array2d, 0, arraySerialized, 0, arraySerialized.Length);
// even works for different dimensions
(again, this is something that could be implemented for List as well, but this feature does not exist in c#)
List<T>
– ratchet freak Dec 10 '14 at 15:31is also just as efficient in memory and performance as an array
- um. Where did you get that notion from? – Oded Dec 10 '14 at 15:33var test = new string[5,5]
;) – Knerd Dec 10 '14 at 15:33