Are array values ​​preserved when redistributing an array in C #?

I worked with my project in Visual Studio in C #, but one thing I don’t know about is that when we redistribute the array (regardless of what type it belongs to), then the previous values ​​that are stored in array destroyed or not? For instance:

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

Now I redistributed the array "a" with 4 elements:

 a=new int[4]; 

Now, will the old values ​​be there or will they change to something new, I mean garbage, zero, or will they be the way they are? I also tried this myself in a visual studio, and the meaning has not changed, but I want to be sure whether this is really not so.

+5
source share
4 answers

Performing this action:

 a = new int[4]; 

you set a to point to another array in another area of ​​memory.

If there are no other references to the old array, it will be in memory until the next garbage collection clears it.

+3
source

If you have other references to the previous array, it still remains 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 processes the array (see Basics of garbage collection ).

Check out the documentation for Array.resize :

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

+2
source

When you write this line

 a=new int[4]; 

a new array is created. a [0] will be 0. If you want to resize the array, use

 Array.Resize(ref a,4); 

This will retain the original values ​​and resize the array.

+1
source

To understand what is going on, you first need to understand what variables really exist. A variable is a placeholder for a value. And what is this value? For value types, a value is an instance of the value type itself; for reference types, a value is simply the memory address, so to speak, of the object to which it refers.

So, when you do the following:

 int[] a = new int[2]; 

Since arrays are reference types, the value stored in a is the address of the newly created array.

Then when you do:

 a = new int[4]; 

The only thing you do is overwrite the value stored in a , which we indicated as just the address of the object referenced.

What happens to the original array? Absolutely nothing, he lives blissfully happy, not knowing that you just reassigned a link pointing to this. If there are no other live links in the original array, then the GC can, if it so decided, compile it, but when that happens, it completely depends on the GC (it may not even happen during the life of your application).

+1
source

Source: https://habr.com/ru/post/1264827/


All Articles