Actually calling myArray[2]
does not add the element, but just assigns the object to the specified index within the array. If the array´s size is less you´d get an IndexOutOfBoundsException
, as in a list<T>
also. So also in case of an array using the indexer assumes you actually have that many elements:
var array = new int[3];
array[5] = 4; // bang
This is because arrays have a fixed size which you can´t change. If you assign an object to an index greater the arrays size you get the exat same exception as for a List<T>
also, there´s no difference here.
The only real difference here is that when using new array[3]
you have an array of size 3 with indices up to 2 and you can call array[2]
. However this would just return the default-value - in case of int
this is zero. When using new List<int>(3)
in contrast you don´t have actually three elements. In fact the list has no items at all and calling list[2]
throws the exception. The parameter to a list is just the capacity, which is a parameter for the runtime to indicate when the underlying array of a list should be resized - an ability your array does not even have.