'Multiple array creation with same name in same scope?
What will be the memory address of arr
, when I am doing arr = new T[size]
twice in the same scope while varying size
?
Does the memory expands to new size and starting address
of arr
remains the same?
Or if the new memory allocation happens then the previous data get copied to new memory location?
using System;
class HelloWorld
{
static void Main ()
{
byte[] arr;
arr = new byte[6];
arr[2] = 6;
Console.WriteLine ("len = {0}\n{1}", arr.Length, arr[2]);
arr = new byte[10];
arr[2] = 10;
Console.WriteLine ("len = {0}\n{1}", arr.Length, arr[2]);
}
}
Solution 1:[1]
According to your coding part first you have initialized the array as
arr = new byte[6];
When you again intializing the array as
arr = new byte[10];
The array will be allocated with a size of 10 and filled with the default value (here 0
). There is no data copy.
And also the byte [6]
will eventually be collected by the garbage collector.
To keep the data in a resized array, you can use Array.Resize
as explained here, but it will change the reference:
var arr = new byte[6];
var arr2 = arr;
Array.Resize(ref arr, 10);
// arr != arr2
Solution 2:[2]
new byte[6]
and new byte[10]
allocate new, different, memory chunks. That is, they will (probably, as mentioned in the comments) not be in the same location in memory.
arr
is not the array itself. It is simply a variable that can hold a reference (the address) to a byte
array. When you are reassigning it, you are simply updating its value to contain a reference to the new memory chunk, while the other one is collected by the Garbage Collector.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Orace |
Solution 2 |