Search code examples
c#structvalue-type

Changing the value of an element in a list of structs


I have a list of structs and I want to change one element. For example :

MyList.Add(new MyStruct("john");
MyList.Add(new MyStruct("peter");

Now I want to change one element:

MyList[1].Name = "bob"

However, whenever I try and do this I get the following error:

Cannot modify the return value of System.Collections.Generic.List.this[int]‘ because it is not a variable

If I use a list of classes, the problem doesn't occur.

I guess the answer has to do with structs being a value type.

So, if I have a list of structs should I treat them as read-only? If I need to change elements in a list then I should use classes and not structs?


Solution

  • MyList[1] = new MyStruct("bob");
    

    structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created).

    In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field.