.net - C#: Variable changes value while processing -
this question has answer here:
my variable changes value while processing. here's code.
private string[] rawlayer; private string[] lastrawlayer; public bool getdisplaymessage(string message) { lastrawlayer = rawlayer; rawlayer[0] = "1"; console.writeline(lastrawlayer[0]); //output = "1" return true; }
why output "1"?
when calling lastrawlayer = rawlayer;
add new reference array rawlayer
instead of creating new array. every change done rawlayer
reflected within lastrawlayer
, vice versa. if want make deep copy of array have re-create it:
lastrawlayer = rawlayer.toarray();
alternativly use array.copyto
:
rawlayer.copyto(lastrawlayer, 0);
which copy every element of rawlayer
second array. if have custom objects stored within array have re-create objects if want avoid change of instance @ index 0 example reflected in both arrays. following still true:
person[] arr1 = new [] { new person { name = "tim" } } person[] arr2 = new person[arr.length]; arr1.copyto(arr2); arr1[0].name = "hans"; // changes value references "tim" console.writeline(arr2[0].name);
the code above print "hans" instead of "tim" because although have different arrays arrays reference same instances of person
.
Comments
Post a Comment