I am vary curious regarding a specific case in c#:
In this code, pointToSourceArr
points to source arr, but if I change sourceArr
by a setting it to a new array or setting it to null, pointToSourceArr
remains with it's two objects :
{ "Itamar", "sasha" }
. Why is that?
string[] sourceArr = new string[] { "Itamar", "sasha" };
string[] pointToSourceArr = sourceArr;
sourceArr = new string[]() // OR NULL;
The value of each variable is just a reference to the array. The assignment here:
just copies the existing value of
sourceArr
intopointToSourceArr
. It doesn't set up a long-lasting relationship between the two variables.Imagine I had a piece of paper with my home address written on it... and then I photocopy that piece of paper and give it to you. If I then cross out the address on my piece of paper, that doesn't change your piece of paper, does it? It's exactly the same here.
Note that if instead you'd change some data within the array, e.g.
then that would be equivalent to me going to my house and painting the front door red - in which case if you then went to the address shown on your piece of paper, you would see a red front door. It's the difference between changing the value of a variable (no other variables are changed) and changing the value within an object (which means anything which can see that object can observe the change).