c# - Altering array while keeping a backup copy -
i have array 3 integers. want duplicate array , change first integer. magical reason, both arrays first integer adjusted. have no idea why happening , it's driving me crazy.
int [] numbers1 = {1, 2, 3} int [] numbers2 = {3, 4, 5} numbers2 = numbers1;
at point did system.console.writeline
see both arrays {1, 2, 3}. far good.
numbers1[0] = 4;
when i'm doing system.console.writeline
see both arrays {4, 2, 3}. want numbers2 stay same.
currently passing reference. numbers in array stored in memory. when reference object in memory points object. not create new object in memory when referencing, need clone ints array points different object in memory.
numbers2 = numbers1;
you need clone arrays.
numbers2 = (int[])numbers1.clone();
as others have noted can use .toarray() method. creates copy of items in array.
numbers2 = numbers1.toarray();
Comments
Post a Comment