Directly modifying List elements

The C# compiler will give you the following error:

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

The reason is that structs are value types so when you access a list element you will in fact access an intermediate copy of the element which has been returned by the indexer of the list.

From MSDN:

Error Message

Cannot modify the return value of
‘expression’ because it is not a
variable

An attempt was made to modify a value
type that was the result of an
intermediate expression. Because the
value is not persisted, the value will
be unchanged.

To resolve this error, store the
result of the expression in an
intermediate value, or use a reference
type for the intermediate expression.

Solutions:

  1. Use an array. This gives you direct access to the elements (you are not accessing a copy)
  2. When you make Map a class you can still use a List to store your element. You will then get a reference to a Map object instead of an intermediate copy and you will be able to modify the object.
  3. If you cannot change Map from struct to a class you must save the list item in a temporary variable:

 

List<Map> list = new List<Map>() { 
    new Map(10), 
    new Map(20), 
    new Map(30), 
    new Map(40)
};

Map map = list[2];
map.Size = 42;
list[2] = map;

Leave a Comment