c# - Cannot modify struct in a list? -


i want change money value in list, error message:

cannot modify return value of 'system.collections.generic.list.this[int]' because not variable

what wrong? how can change value?

struct accountcontainer {     public string name;     public int age;     public int children;     public int money;      public accountcontainer(string name, int age, int children, int money)         : this()     {         this.name = name;         this.age = age;         this.children = children;         this.money = money;     } }  list<accountcontainer> accountlist = new list<accountcontainer>();  accountlist.add(new accountcontainer("michael", 54, 3, 512913)); accountlist[0].money = 547885; 

you have declared accountcontainer struct. so

accountlist.add(new accountcontainer("michael", 54, 3, 512913)); 

creates new instance of accountcontainer , adds copy of instance list; and

accountlist[0].money = 547885; 

retrieves copy of first item in list, changes money field of copy , discards copy – first item in list remains unchanged. since not intended, compiler warns this.

solution: not create mutable structs. create immutable struct (i.e., 1 cannot changed after has been created) or create class.


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -