c# - Unable to update the contents of a Generic List -


i have simple class has boolean field:

public struct foo { bool isavailable; } 

now have list of foos:

list < foo >  list = new list< foo >(); 

later on enumerate each foo in list , try update isavailable field:

foreach(foo foo in list) {     foo.isavailable = true;  } 

but above code never updates list. doing wrong here , what's remedy.

it's because foo mutable struct.

when fetch value list, it's making copy - because that's how value types behave. you're changing copy, leaving original value unchanged.

suggestions:

  • you should using class
  • don't create mutable structs. behave in ways can hard predict, or @ least not way might expect when you're not explicitly thinking it.

while could change code iterate on list in different way , replace value each time, it's bad idea so. use class... or project list new list appropriate values.


original answer, when foo class

it should work fine. example, here's short complete program does work:

using system.collections.generic;  public class foo {     public bool isavailable { get; set; }     public string name { get; set; }      public override string tostring()     {         return name + ": " + isavailable;     } }  class test {     static void main()     {         list<foo> list = new list<foo>()         {             new foo { name = "first", isavailable = true },             new foo { name = "second", isavailable = false },             new foo { name = "third", isavailable = false },         };          console.writeline("before:");         list.foreach(console.writeline);         console.writeline();          foreach (foo foo in list)         {             foo.isavailable = true;         }          console.writeline("after:");         list.foreach(console.writeline);     } } 

try adapt current code similar short complete program doesn't work, post that, , can work out what's going on.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -