Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why arrays needs dimension set at define time?

Tags:

arrays

c#

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;
like image 799
Jake Manet Avatar asked Nov 29 '22 15:11

Jake Manet


2 Answers

Because arrays are contiguous in memory, you have to allocate enough memory for its contents when you create it.

Say you have an array with 100 items in it. Now you add 1 more, and you have to claim the memory address right after the 100th item. What if that address is already being used?

That's why you can't dynamically resize an array.

like image 33
dcastro Avatar answered Dec 12 '22 12:12

dcastro


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...

like image 107
Jon Skeet Avatar answered Dec 12 '22 12:12

Jon Skeet