-2

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++;
    }
Min
  • 55
  • 1
  • 6
  • 3
    The value of `aPaintAction2` is just a *reference* to the list. Both your `AnnotationAction` and `aPaintAction2` will have a reference to the same list. See http://jonskeet.uk/csharp/references.html for more details – Jon Skeet Oct 18 '18 at 15:22
  • just clone aPaintAction2 and than add it . – Gaurav Moolani Oct 18 '18 at 15:30
  • 1
    I would strongly recommend reading a good book or tutorial at this point. It's *really* important that you understand how reference types work in .NET, or you'll get really confused. (Note that my article isn't trying to provide guidelines, just information.) – Jon Skeet Oct 18 '18 at 15:41
  • @GauravMoolani how to clone it? – Min Oct 18 '18 at 15:45
  • @JonSkeet Thank you JonSkeet. As I have self low-esteem I tend to delete reply that sounds stupid... haha.. After reading your link several times, I understood the difference between value type and reference type. But I don't know how to solve this. – Min Oct 18 '18 at 15:50
  • @Min there are two ways to clone . Serialize and deserialize and other is expression tree. https://stackoverflow.com/questions/78536/deep-cloning-objects. https://www.codeproject.com/Articles/1111658/Fast-Deep-Copy-by-Expression-Trees-C-Sharp. Expression tree is faster and takes less memory. – Gaurav Moolani Oct 19 '18 at 03:47

1 Answers1

0

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.

Robin Bennett
  • 3,192
  • 1
  • 8
  • 18