C# struct in a list

25,393

Solution 1

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.

Solution 2

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;
Share:
25,393
bwoogie
Author by

bwoogie

I like to program, sometimes. SOreadytohelp

Updated on November 20, 2020

Comments

  • bwoogie
    bwoogie over 3 years

    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
    bwoogie over 8 years
    This is what I ultimately did, but I was curious as to why I was getting that error. Thanks.