Search code examples
c#listpointmouseup

c# Object parameter mysteriously cleared after assigned a parameter


I am a newbie to C#. I want to collect all the points for a Paint action in MouseUp event. After I pass in the parameters from aPaintAction2 into Actions2, I clear the content of aPaintAction2. Somehow, after the aPaintAction2 content is cleared, the parameter value in Actions2 (that aPaintAction2 passed in) is also cleared.

Can someone explain to me what is this problem and why is this happening? I just want to pass in the points aPaintAction2 holds into Actions2, Actions2 keeps the points parameters, and clear aPaintAction2 so that aPaintAction2 can hold new points. Thank you.

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (moving && x != -1 && y != -1)
        {
            aPaintAction2.Add(e.Location);
            x = e.X;
            y = e.Y;
        }
    }

    private List<AnnotationAction> Actions2 = new List<AnnotationAction>();
    private List<Point> aPaintAction2 = new List<Point>();
    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        // save a Paint action
        Actions2.Add(new AnnotationAction(newActionId, pen.Color, pen.Width, aPaintAction2));

        aPaintAction2.Clear();

        moving = false;
        x = -1;
        y = -1;
        newActionId++;
    }

Solution

  • Instead of

    aPaintAction2.Clear();
    

    which removes all items from the list, try:

    aPaintAction2 = new List<Point>();
    

    which will create a new empty list, but leave the old list in the Actions.