Domanda

I have created an IList variable as below:

IList<vertex> matrix = new List<vertex> ();

Here, vertex is a structure I defined with one of the members being visited (boolean).

But, when I try to modify this member by traversing through the list as below:

matrix[j].visited = false;

It gives an error saying "Cannot modify return value because it is not a variable". Any idea why?

È stato utile?

Soluzione

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.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top