How array allocation is implemented in c#?

E

efi_hoory

Hi, I undetstand that array allocation in c# is not preformed when I call to new operator. Allocation is done only when I set a value in tha array.

My question is if I put values in part of the array, all the array is allocated or only a part of it?

For example, if I have an array of 1000 bytes, and I fill the first 100 bytes, the size of the allocation memory for this array is 100 or 1000?

Efi.
 
A

Arne Vajhøj

Hi, I undetstand that array allocation in c# is not preformed when I call to new operator. Allocation is done only when I set a value in tha array.

Not correct.
My question is if I put values in part of the array, all the array is allocated or only a part of it?
All.

For example, if I have an array of 1000 bytes, and I fill the first 100 bytes, the size of the allocation memory for this array is 100 or 1000?

1000.

Note that arrays of value types and reference types had to be treated
slightly different by your code.

int[] a = new int[25];

allocates an int array with 25 elements all set to the default value of
int which is zero - consider it a chunk of 100 contiguous bytes.

And you just use the elements:

a = i;
Console.WriteLine(a);

MyClass[] a = new MyClass[25];

allocates an array of MyClass references with 25 elements all set to
null - consider it a chunk of 100 (32 bit CLR) or 200 (64 bit CLR)
contiguous bytes.

Before you can really use an element then you need to have
the references point to some objects.

So:

a = new MyClass();

if you do this for all 25 elements in the example then you have
26 objects - 1 array of MyClass object and 25 MyClass objects.

After than you just use the elements:

a.SomeMethod();

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top