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 -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -