Probably my favorite class in C# is the List
. It expands to hold as many items as you want, and it can be set (through the generics syntax) to hold any element type you desire. But arrays in C# offer some clear benefits, too—though they are less often needed.
An array is different from a List
mainly because it cannot resize its buffer on its own. An array of 100 elements will always have 100 elements (though elements could be null
). For this reason, we should prefer arrays only when we know the exact element count beforehand—like for a buffer of bytes we read data into.
Arrays are preferred only when:
Basically, if your program's goal is to read strings from a file, you will want a List. But if you want to store 10 strings in a class for later use, a string
array is a better choice. Usually the List
is the better first choice.