Question

I want to create a aminator class. But it can't modify the field value in other classes.

Here is my simplified animator class:

public class PointMover
{
    Point point;
    public void Set(ref Point p)
    {
        point = p;
    }

    public void Move(int dX)
    {
        point.X += dX;  // The point.X is modified here.
    }
}

and my main class:

public partial class Form1 : Form
{
    PointMover pointMover = new PointMover();
    Point point = new Point(0, 0);

    private void Form1_Load(object sender, EventArgs e)
    {
        pointMover.Set(ref point);
        pointMover.Move(10); // But point.X is NOT modified here.
        this.Close();
    }
}

Here is my problem. Is there anyone knows how to fix it? I'll be appreciate it.

Was it helpful?

Solution

Point is a struct (i.e. value type). You pass it by reference, but you then create copy of point instance in constructor of PointMover by assigning it to point field:

public void Set(ref Point p)
{
    point = p; // here you create copy of passed point
}

Thus modifications of point don't affect p (because they represent different instances of structure).

Note: If Point would be a reference type (i.e. class) then this assignment would copy a reference, and both variables would have references to same instance in heap.


In order to fix this behavior, you need to modify point which was passed by reference without creating copy. E.g.

public static void Move(ref Point point, int dX)
{
    point.X += dX; 
}

Usage:

PointMover.Move(ref point, 20);

Or you can simply use Point.Offset(int dx, int dy) method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top