2

Quick question about structs... I have a struct, lets pretend it looks like this:

struct myStruct {
     public int x, y;
}

And then I make a list filled with that struct

List<myStruct> myList = new List<myStruct>;

And then later I loop through the list and I want to change the value of x...

for(int i=0; i<myList.Count; i++) {

     ...//do stuff to x

     myList[i].x = newX;
}

Cannot modify the return value of 'List<myform.myStruct>.this[int]' because it is not a variable

Can you please clear up any confusion I'm having as to why it's not letting me change the value of x.

bwoogie
  • 4,339
  • 12
  • 39
  • 72
  • 8
    This is why you should never make mutable structs. – SLaks Nov 19 '15 at 16:56
  • Question has already been asked http://stackoverflow.com/questions/51526/changing-the-value-of-an-element-in-a-list-of-structs –  Nov 19 '15 at 17:01
  • 1
    If you need to mutate the values in the list, why not use a `class` instead like `Tuple`? – juharr Nov 19 '15 at 17:01

2 Answers2

4

A struct is a value type, and is passed by value. When you say myList[i].x = newX you're assigning to the x property of a copy of the ith element of myList, which would be thrown away after the statement is executed. Luckily the compiler will stop you from making this mistake.

Gary McGill
  • 26,400
  • 25
  • 118
  • 202
4

Structs are value types. So the return of the indexer is a temporary copy of the value in the list which cannot be modified. You have to replace the struct in the list:

var val = myList[i];
val.x = newX;
myList[i] = val;
clcto
  • 9,530
  • 20
  • 42