0

I have the following code:

for (int i = 0; i < 10000; i++ )
{
    list.Add(new Point(i, 3));
}

for (int i = 0; i < 10000; i++)
{
    list[i].X = 100;
}

Point point = new Point(0, 1);
point.X = 1;
point.Y = 10;

When I try to change X or Y property of a newly created Point structure there is no problem:

Point point = new Point(0, 1);
point.X = 1;
point.Y = 10;

But when I'm trying to do the same in a loop

for (int i = 0; i < 10000; i++)
{
    list[i].X = 100;
}

The compiler is telling me

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

Can anybody please explain me this.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • See [duplicate](http://stackoverflow.com/questions/51526/changing-the-value-of-an-element-in-a-list-of-structs) for a thorough explanation, but basically and simplified: by calling `list[i]` you get a copy of the list item at index `i`. The compiler prevents you from doing useless things, as `list[i].X = 100;` wouldn't really do anything (apart from modifying a copy that would go out of scope immediately). – CodeCaster Aug 16 '15 at 11:09
  • Thank You, but is there some workaround to this? In a duplicate they are using interface but at the same time they are talking about custom structure. And I'm bind to Point structure. And I cannot just do it like this: list[i] = new Point(100,0) – user4958960 Aug 16 '15 at 11:14
  • Why can't you just do that? It's how you should do it. When modifying a struct list, you have to re-assign the item (`list[i] = new Point(100, 0)`). – CodeCaster Aug 16 '15 at 11:15
  • I would say, [**this**](http://stackoverflow.com/questions/16222757/setting-y-coordinate-of-system-windows-point-from-a-list-gives-modify-error) will be a better solution for your problem. – Raging Bull Aug 16 '15 at 11:18
  • Because of performance issues. I struggle to avoid creating new instances of Point structures because its a bottleneck of my program. – user4958960 Aug 16 '15 at 11:20

0 Answers0