TheNormalPotato TheNormalPotato - 2 months ago 6
C# Question

How to tie one variable to another

I have this bit of code:

Brick brick1= new Brick(parent.X - 1,parent.Y);


X & Y are integers,

Basiclly what i want to do is: when the x of the parent brick changes, the x of brick1 changes,where it dosnt matter the value of
parent.X
,
brick1.X
will always be equal to
parent.X - 1


Is there an way of accomplishing this?

Answer

Assuming that Brick is not a struct you could do this. You could also do this through inheritance with a ChildBrick class but unless you need the added complication, at least in my mind, it is simpler to just allow Brick to have a parent that is a Brick and add a constructor for the parent. Then if you retrieve a value and it needs to be computed from the parent you just check for whether you have a parent and calculate accordingly.

class Brick
{
    private Brick _parent;
    private int _x;
    private int _y;

    Brick(Brick parent) {_parent = parent);}
    Brick(int x, int y)
    {
        _x = x;
        _y=y;
    }

    public int X
    {
        get
        {
            if (_parent != null) return _parent.X - 1;
            return _x;
        }
    }
    public int Y
    {
        get
        {
            if (_parent != null) return _parent.Y;
            return _y;
        }
    }
}