i have problem using c#, if initialize list, lets list<t> examplelist
using pre-existing list, lets tomodify this: list<t> examplelist = new list<t>(tomodify)
. when later modify tomodify list newly created list modifies itself. if passes value reference shouldn't value of examplelist stay same since generated other one?
tldr: value of list initialize using list(second list) changes when change second list. come java background , can't understand why happens. have use clone?
let use example :
list<a> firstlist = new list<a>() { new a() { id = 3 }, new a() { id = 5 } }; list<a> secondlist = new list<a>(firstlist); secondlist[1].id = 999; console.writeline(firstlist[1].id);
output : 999
the main reason though create new list<t>
object (yes collection object well) points new memory allocated in managed heap still works references same objects.
to create list of new (!) objects same values need clone elements somehow, 1 way use linq .select()
method create new objects , tolist()
method convert list :
list<a> firstlist = new list<a>() { new a() { id = 3 }, new a() { id = 5 } }; list<a> secondlist = firstlist.select(el => new a() { id = el.id }).tolist(); secondlist[1].id = 999; console.writeline(firstlist[1].id);
output : 5
Comments
Post a Comment