c# - Added item value changes after item property clear -


i have list , when clear notes property of list after add list below example clears added item of stdlist. didn't understand why? please me :(

list<student> stdlist = new list<student>(); student std = new student(); std.notes = new list<string>(); std.notes.add("ee"); stdlist.add(std); std.notes.clear(); 

it changes because when add student object, adds reference object in list. reference added still point same object, modified. change object reflected in list.

here demo:

stringbuffer sb = new stringbuffer("aa");  list<stringbuffer> list = new arraylist<stringbuffer>(); list.add(sb); system.out.println(list);  sb.append("bb"); system.out.println(list);  sb = null; system.out.println(list); 

output:

aa aabb aabb 

and don't forget, when deal objects strings, immutable, new object created on change operations. old object still in list while got new 1 elsewhere.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

node.js - Express and Redis - If session exists for this user, don't allow access -

excel - I can't get the attachement of the email PHP -