Changing the value of a List <Point> item
I am making a (school) curve drawing application. I set the points with a mouse click and add their positions to the list of vertices. Now I'm working on moving glasses using mouse and mouse actions. When washing the mouse, I will find out if the mouse position is in a small square (4x4 px) around any vertex in the list of vertices, and then on the mouse up. I want to change the coordinates of the vertis to the coordinates where I lifted the mouse button up. But I ran into the List
problem because the visual studio says that the elements of the list cannot be changed because it is not a variable. How can i solve this?
List<Point> vertices = new List<Point>(); //list of vertices void canvas_MouseUp(object sender, MouseEventArgs e) { if (!move) return; //if moving is off returns vertices[indexOfMoved].X = eX; //change X position to new position vertices[indexOfMoved].Y = eY; //change Y position to new position indexOfMovedLabel.Text = "Moved: ?"; }
Problem:
Error 1: Cannot change the return value of 'System.Collections.Generic.List.this [int]' because it is not a variable
This is because Point
is a structure, not an object. You can view structures as grouped values.
So, when you access the vertices of [indexOfMoved], you get a copy of what is on the list, not the actual โobjectโ.
You can do it as follows:
vertices[indexOfMoved] = new Point { X = eX, Y = eY };
You cannot change this value because Point is a structure. Before giving a lot of details; you need to change your function to the following:
private void canvas_MouseUp(object sender, MouseEventArgs e) { if (!move) return; //if moving is off returns Point p = vertices[indexOfMoved]; pX = eX; pY = eY; vertices[indexOfMoved] = p; indexOfMovedLabel.Text = "Moved: ?"; }
This will cause you to use a structure. If the compiler did not issue any warnings, then a new structure will be created on the stack and changes will be made to the structure on the stack; which will not affect the structure in the list. The compiler gives a warning to prevent this.