c# - Creating a grab-bag (collection) of original references to objects -


i'm looking type/method of collection can add object group of objects, separately change attributes of object, , have changes reflected in object within collection.

i've heard list<t> adds values reference, figured reference same object. in other words, assumed:

list<string> valueslist = new list<string>(); string initialvalue = "alpha"; valueslist.add(initialvalue);  initialvalue = "bravo"; bool incorrectassumption = (valueslist[0] == "bravo"); 

i had hoped 'valueslist' contain new value, "bravo." tried out , realized list copies reference, doesn't absorb it, valuelist still has "alpha" value. there ways use collection legitimate handful of objects contain?

and in case helps see actual business need....

list<basewidget> widgets = new list<basewidget>();  derivedwidget specialwidget = new derivedwidget(); derivedwidget extraspecialwidget = new derivedwidget();  widgets.add(specialwidget); widgets.add(extraspecialwidget);  specialwidget.run(); extraspecialwidget.run();  if (!widgets.any(x => x.runsuccessfully)) return false; 

(where run() method sets runsuccessfully property, i'd have reflected in 'widgets' list.)

============================================================================

update

as it's been pointed out in answers , comments, there's bit of discrepancy between business need mock-up , dry-run example. i'll condense life-lesson this: seems list<objects> have changes tracked, whereas list<values> don't.

all references non-value types passed reference, list<t> or not. string value type, however, , passed value. immutable, time change 1 you're creating new string.

for example, create wrapper type contain string, , store in list<t>.

it seems actual business case should work properly, unless declared structs.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -