Reputation: 309
Let's say I have the following code:
float[] test = new float[10];
for(int i = 0; i < 10; i++)
{
test[i] = i + 1.0f;
}
and I reassign a new float to test array like this:
test = new float[10];
After debugging through Console.WriteLine, it shows that the value of the reassign test
is 0. Does that mean test
is a reference to a newly created float array, or the previous array is being cleared and recreate again?
I have read some articles about heap and stack but that didn't resolve my confusion.
Upvotes: 0
Views: 893
Reputation: 6613
Let me give you a more detailed example:
float[] test = new float[10];
float[] test2 = new float[10];
test = Enumerable.Range(10, 10).Select(x => (float)x).ToArray();// 10 - 20
test2 = Enumerable.Range(20, 10).Select(x => (float)x).ToArray();// 20 - 30
float[] testBak = test;
test = test2;
test[0] = 1;
Console.WriteLine(test[0]);// prints 1 as it was just modified
Console.WriteLine(test2[0]);// prints 1 because it has the same value of the reference as 'test'
Console.WriteLine(testBak[0]);// prints 10 which is the old value of test[0]
I have rewritten your code using two variables to hold both references of the arrays (which are value types). What you are doing when you are making an assignment is changing the value of the reference which that variable is holding to another value of another reference.
The memory locations which the two arrays hold are still different even after assignment, you are just keeping in your variable another address. This is why if you change the value of one of the entries in the first array, it will be visible in all the variables holding the same reference of that array, but not in the variables holding the reference of another one (as testBak
holds an older reference).
Upvotes: 0
Reputation: 52185
Deep down, test
is a pointer to a chunk of memory of size sizeof(float) * 10)
(the chunk might be a bit larger, but that is outside the point).
Within the loop, you start putting values within that chunk of memory. Then, when you do test = new float[10];
, the CLR will give you a new pointer to a new chunk in memory.
The previous chunk in memory will be reclaimed by the garbage collector (unless it is being used some place else) at some point in the future.
Upvotes: 6