winforms - Adding custom objects to checked list boxes in C# -


i have object stores 2 strings , overrides tostring() method return 1 of strings

            foobar temp;             foreach (string foo in bar)             {                 temp = new foobar(); <--- why line needed when                  overwriting code , path on each cycle before adding?                  temp.code += ".";                 temp.path += ".";                  console.writeline(temp);                 clbfoobar.items.add(temp);             } 

the prints console obey overwritten code , path string values, checked list box items same thing (the last item's tostring()), underlying process going on isn't obvious?

if change clbfoobar.items.add(temp.tostring()); works absolutely fine, wouldn't same temp.tostring.tostring() because .add calls .tostring() in first place? figured both console print , .add act same seeing both call tostring()

edit: temp = new foobar(); fix problem, want know why fix when intuition leads me think overwriting 2 strings, code , path, should enough , why without re-initialisation, of items in checked list box same.

so you're question seems why code works correctly if keep line

temp = new foobar(); 

in loop, fill checkedlistbox equal items if ommit line.

the reason if create only one instance of foobar outside loop that:

foobar temp; = new foobar(); foreach (string foo in bar) {     temp.code += ".";     temp.path += ".";     clbfoobar.items.add(temp); } 

then adding same instance multiple times, , change properties of instance in each iteration.

if create new instances inside loop that:

foreach (string foo in bar) {     foobar temp; = new foobar();     temp.code += ".";     temp.path += ".";     clbfoobar.items.add(temp); } 

you have new instance every iteration , don't change added instances.


update: noticed still same set them whatever default value code , temp have plus ".". it's still little unclear try do. maybe this:

string s = string.empty; foreach (string foo in bar) {     s += ".";     foobar temp; = new foobar();     temp.code = s;     temp.path = s;     clbfoobar.items.add(temp); } 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -