Can't change the structure in the list?

I want to change the monetary value in my list, but always get an error message:

It is not possible to change the return value of 'System.Collections.Generic.List.this [int]' because it is not a variable

What's wrong? How to change the 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; 
+6
source share
4 answers

You declared AccountContainer as struct . So

 AccountList.Add(new AccountContainer("Michael", 54, 3, 512913)); 

creates a new instance of AccountContainer and adds a copy of this instance to the list; and

 AccountList[0].Money = 547885; 

extracts a copy of the first element in the list, changes the Money field of the copy and discards the copy - the first element in the list remains unchanged. Since this is clearly not what you intended, the compiler warns you about this.

Solution: do not create mutable struct s. Create an immutable struct (i.e., one that cannot be modified after its creation) or create a class .

+8
source

You are using evil mutable structure.

Change this to a class and everything will work fine.

+9
source

Here is how I would solve this for your scenario (using the immutable struct method, rather than changing it to class ):

 struct AccountContainer { private readonly string name; private readonly int age; private readonly int children; private readonly 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; } public string Name { get { return this.name; } } public int Age { get { return this.age; } } public int Children { get { return this.children; } } public int Money { get { return this.money; } } } List<AccountContainer> AccountList = new List<AccountContainer>(); AccountList.Add(new AccountContainer("Michael", 54, 3, 512913)); AccountList[0] = new AccountContainer( AccountList[0].Name, AccountList[0].Age, AccountList[0].Children, 547885); 
+1
source

Probably not recommended, but it solves the problem:

 AccountList.RemoveAt(0); AccountList.Add(new AccountContainer("Michael", 54, 3, 547885)); 
0
source

Source: https://habr.com/ru/post/945520/


All Articles