When you fetch the vertex
using the IList<T>
indexer, that will return a copy of the value. Changing that copy wouldn't change the list - so the compiler stops you from writing incorrect code.
Options:
- Make
vertex
a class instead of a struct. A class is a reference type: the list would contain references, and changes to the objects that those references refer to would be visible via the references later. Keep
vertex
as a struct, but change your code to:vertex v = matrix[j]; v.visited = false; matrix[j] = v;
Keep
vertex
a struct, but make it immutable - mutable structs can cause all kinds of issues. Provide a method to create a new value from an existing one, but with one particular change. You can then call that method on the result of fetching with the indexer, and set the new value using the setter:matrix[j] = matrix[j].WithVisited(false);
Personally I suspect the last option is likely to be the best one - a vertex may well be a natural value type. I would strongly encourage you to start following .NET naming conventions though - the type should be Vertex
and visited
should probably be Visited
. (The one exception would be if this code is within the vertex
type, and it's referring to a field. The field should be private, and other code would need to use a property to access the value.)