Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does values of array destroyed when we reallocates a array in c#?

I was working with my project in Visual studio in c#, but one thing I don't know about is that when we reallocate a array (no matter what type it is of) then does the previous values that stored in the array are destroyed or they are not? For Example:

int[] a=new int[2];
a[0]=200;
a[1]=400;

Now I reallocated the array 'a' with 4 elements:

a=new int[4];

Now, does the previous values will be there or they changed to something new value, i mean garbage, zero or they will be as they was? I also tried it myself in visual studio, and value didn't changed, but I want to be sure if really they don't.

like image 414
jimmy Avatar asked Feb 28 '17 10:02

jimmy


2 Answers

Doing this:

a = new int[4];

you set a to point to another array in another memory region.

If there is no another references to old array it will be in memory until next garbage collection clears it.

like image 133
Roman Doskoch Avatar answered Nov 18 '22 07:11

Roman Doskoch


When you have any other references to the former array it still stays in memory.

int[] a=new int[2];
a[0]=200;
a[1]=400;

int[] additionalReference = a; // The array stays in memory 
a = new int[4];

Otherwise the garbage collector handles the array (see Fundamentals of Garbage Collection).

Check the documentation of Array.resize:

This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.array must be a one-dimensional array.

like image 2
Kevin Wallis Avatar answered Nov 18 '22 08:11

Kevin Wallis