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

This error is shown when an attempt to assign a value to a property inside a struct.

e.g

System.Drawing.Point p = new Point();
p.X = 1; //legal of course

Listlist = new List();
list.Add(p);
list[0].X = 123; //Cannot modify the return value of System.Collections.Generic.List.this[int]‘ because it is not a variable

Remember structs are value types. They are processed like integers and only assigned as a whole.
Therefore when accessed from a list a copy of the struct is returned. Assigning to the copy is pointless, hence the error.

You can assign one member by using the following method

System.Drawing.Point p = list[0];
p.X = 123;
list[0] = p;

Lastest update in December 2011, inital post in December 2011

Write a comment

I appreciate comments, suggestions, compliments etc. Unfortunately I have no time to reply to them. Useful input will be used for sure!