0

I want to get pointer to the rectangle from list. But Rectangle is struct and when I try to get pointer I get copy.

Class MyClass
{
    Rectangle MovingRectangle;
    List<Rectangle> RectangleList;
    Point StartLocation;

    ***some code here***

    void PicBoxMouseDown(object sender, MouseEventArgs e)
    {
        foreach (rectangle in RectangleList)
        {
            if (condition) 
            {
                MovingRectangle = rectangle;
                StartLocation = e.Location;
                break;
            }
        }
    }

    void PicBoxMouseMove(object sender, MouseEventArgs e)
    {
        MovingRectangle.Location =
                new Point(movingRectangle.Location.X + (e.X - StartLocation.X),
                          movingRectangle.Location.Y + (e.Y - StartLocation.Y));
    }

}

I want to change rectangle position in List, but i change position of copy.

super sahar
  • 375
  • 1
  • 3
  • 13
  • I don't see you "changing rectangle position in List" in your code. But, they way you'd change a rectangle's position in a list would be to remove it from it's old position and insert it into a new position. Copying a rectangle (which is what this entails) isn't much more work than copying a reference (what you'd do if Rectangle were a class rather than a struct) – Flydog57 Feb 12 '19 at 19:07
  • You could and probably should create a class with the rectanlge and some other fields you already have in your code. Always plan for growth! – TaW Feb 12 '19 at 21:16

1 Answers1

3

Instead of storing a copy of the rectangle, store the index of the rectangle and then re-assign the whole rectangle.

int MovingRectangleIndex;
List<Rectangle> RectangleList;
Point StartLocation;

void PicBoxMouseDown(object sender, MouseEventArgs e)
{
    for (int i = 0; i < RectangleList.Count; i++) {
        if (condition) {
            MovingRectangleIndex = i;
            StartLocation = e.Location;
            break;
        }
    }
}

void PicBoxMouseMove(object sender, MouseEventArgs e)
{
    var rect = RectangleList[MovingRectangleIndex];
    RectangleList[MovingRectangleIndex] = new Rectangle(
        rect.X + e.X - StartLocation.X,
        rect.Y + e.Y - StartLocation.Y,
        rect.Width, rect.Height);
}

This is the only way of changing a property of a struct in a list. It is however possible to change a property of an element in a struct array. The difference is that the list has an indexer (i.e. a pair of get and set methods) where the get method returns a copy of the element, whereas the array has a true index. I.e., indexing an array returns the position inside the array. An array is a fundamental type supported by the C# compiler. A list is implemented as ordinary class in the library. The C# compiler does not have a specific knowledge of lists.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188