-1

Maybe it's a very simple thing, but I'm asking out of curiosity. I think the above situation is a logic error that should not have happened. There are two arrays. First array element number 10. Second array element number 20. When you equate the second array to the first array, it directly includes the values. But I set the size of the first array to be 10.

How is this possible?

Example Code

int[] array1 = new int[10];
int[] array2 = new int[20];
public MainWindow()
{
    InitializeComponent();
    array1 = array2;
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 2
    You are not changing the individual items in `array1` when you do that, you are changing the _reference_ of `array1` to point to `array2` – maccettura Dec 19 '20 at 23:59

3 Answers3

4

One of the fundamental things to understand about C# is that the variables array1 and array2 are references to in-memory array instances.

When you run the code

array1 = array2;

You are not writing the values of array2 into array1.

You are making it that array1 and array2 are pointing to the same instance.

Repeating, array1 will not be a copy of array2. After the assignment, the two variables are literally the same array.

The initial 10-element array that array1 was pointing to is now dereferenced. The garbage collector will soon reclaim the memory it occupied.

Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
1

To better understand this you need to know the different between a Reference Type and Value type. You can get more information here.

Now, an array is of Refence type as explain here. So when you do this:

array1 = array2;

array1 is now referencing the same reference in memory that array2 has. This means that any change to either array1 or array2 will be reflected on both arrays as they both point to the same reference.

DaGs
  • 81
  • 5
0

Here your are not copying the actual values of array2 into array1. But you are just changing the reference of array1 to the reference which array2 is holding in the heap. If you actually want to copy the values do it using loops or streams. This is not the right way to achieve what you are trying to

  • Thank you for your answer. I understand very well. Question marks disappeared. –  Dec 20 '20 at 00:04