Why arrays needs dimension set at define time?

I am just wondering, why can't we just define something like this:

int[] arr = new int[];
arr[0] = 1;

Like a list, to resize automatically. What i want to know is why is this impossible and we need to set every time the size in the following way:

int[] arr = new int[1];
arr[0] = 1;
Jon Skeet
people
quotationmark

List<T>'s resizing is based on creating a new array behind the scenes when it needs to.

Think about what the underlying implementation looks like here. When you allocate an array, it reserves a chunk of memory, and the reference effectively points straight at that memory. If you need to store more values than you've reserved, you need to allocate more memory, somewhere else... but you can't change the reference to refer to that new memory, because those references are spread all over the place. (The array doesn't know what's referring to it.)

The obvious way around this is to have a level of indirection - so that the initial reference is to an object which keeps track of where the real data is stored, so it can reallocate when it wants to. That's exactly what List<T> does... but it does mean there's that extra level of indirection. That has a cost in efficiency, partly as you may well have the actual data a long way in memory from the List object itself, which isn't good for caching... and simply going through an extra level of indirection has a cost in itself.

Basically if you want a dynamically sized collection, use List<T> - that's what it's there for. If you know the final size from the start and want to benefit from the "nearer to the metal" aspect of arrays, use those instead.

Arrays are a relatively low level concept - if you want a high level abstraction, use one...

people

See more on this question at Stackoverflow