c# - Why Collection assignment act differently inside method and consecutive lines? -
from below results, know why 'test 2' have value 30 , expect same result in 'test 3' (100) ?
here fiddler link https://dotnetfiddle.net/rco1md better understanding.
ilist<test> initialcollection = new list<test>(); initialcollection.add(new test(){ value = 30}); console.writeline("test 1 : before update method : " + initialcollection.last().value ); updatevaluecollection(initialcollection); console.writeline("test 2: after update method : " + initialcollection.last().value ); ilist<test> check = new list<test>(); check.add(new test(){ value = 100}); initialcollection = check; console.writeline("test 3: same update method code added consecutive line : " + initialcollection.last().value );
and method is
public void updatevaluecollection(ilist<test> lsttest) { ilist<test> check = new list<test>(); check.add(new test(){ value = 100}); lsttest = check; }
the results are
test 1 : before update method : 30 test 2 : after update method : 30 test 3 : same update method code added consecutive line : 100
before second test pass copy of value in initialcollection
updatevaluecollection
, in method disregard value passed, create new list, , modify list. method never have observable effects on caller of method.
before test 3 create new list, give value, , assign initialcollection
, mutating value of variable. since have changed value of variable, unlike second test, has caused observable effect when later value of variable.
had method updatevaluecollection
passed parameter by reference (through use of ref
or out
keywords) instead of by value, changes parameter have affected initialcollection
, passed value, copy of variable mutated.
note if wished updatevaluecollection
compute new list variable more idiomatic design have updatevaluecollection
return new list instead of being void
, , assign value of method initialcollection
.
Comments
Post a Comment