Update the property of a struct within a List in C#

c#, struct

Solution

Since `struct`s are value types, and because value types get copied, `myCat` ends up with the copy of the cat from the list. You need to operate on the `struct` itself, not its copy.

Moreover, you can modify fields of `struct`s directly only when they are single variables or parts of an array. `List<T>`'s indexer returns a copy, so C# compiler produces the "Cannot modify a value type" error.

The only solution that I know (short of making `Cat` a `class` or re-assigning a modified copy) is making `catList` an array:

var indexOf = catArray
    .Select((Cat, Index) => new {Cat, Index})
    .Single(p => p.Cat.Id == 7).Index;
catArray[indexOf].Name = "Dr Fluffykins";

Problem

I have a `List<Cat>` where `Cat` is a `struct` that has an Id and a Name. How do I change the name of the cat with id 7? I did (without thinking) ``` var myCat = catList.Single(c => c.Id == 7); mycat.Name = "Dr Fluffykins"; ``` But of course, structs are value types. So is it possible to use a technique like this, or do I have to change `.Single` into a `for` loop and store the index to replace it with the updated struct?

Original source

Related problems