I have list of structure. I want to modify a particular data from the structure.
And the structure is at the particular index location of the List.
I want to do something like this:
struct sample
{
int a;
string name;
}
List<sample> list = new List<sample>();
for(int i=0; i < list.Count; i++)
{
list[i].a = someotherlist[i].data;
}
The problem is that the list indexer creates a copy of the struct, i.e. it is really:
The compiler is preventing you making an obvious mistake. The code you have uses the
get, mutates a separate copy of the data, but never puts it back – so your change doesn’t do anything useful. Note that the Mono folks think it would be nice if it worked your way, though: http://tirania.org/blog/archive/2012/Apr-11.htmlNote that an array works differently; with an array you are touching the struct in place, so the following would work fine:
Another approach is to copy the data out (the get accessor), mutate it, and put it back:
or better, acoid mutable structs completely, perhaps with a method that applies the change to a new copy:
where
SetAcreates a new struct, likeDateTime.AddDaysetc, i.e.