Search code examples
c#getter-setter

Property set not getting used when changing a property of the property


I have a super simple class Point:

class Point
{
    public Point(double x, double y)
    {
        X = x;
        Y = y;
    }

    public double X;
    public double Y;
}

I use Point in a Box class:

internal class Box
{
    private Point _upperLHCorner = new Point();
    private Point _lowerRHCorner = new Point();

    internal Box() { }

    public Point UpperLHCorner
    {
        get
        {
            return _upperLHCorner;
        }

        set
        {
            this._upperLHCorner = value;
            _lowerRHCorner.X = _upperLHCorner.X + _width;
            _lowerRHCorner.Y = _upperLHCorner.Y + _height;
        }
    }

    public Point LowerRHCorner
    {
        get
        {
            return _lowerRHCorner;
        }
    }
}

When I set UpperLHCorner.X in my code the setter for UpperLHCorner is not getting called. Instead the getter is called. I need to change the LowerRHCorner backing variable x and y when appropriate. How do I do this?


Solution

  • You can't use the setter of UpperLHCorner to modify the properties of _lowerRHCorner. The only time setter is called is if you assign a new value to UpperLHCorner itself. To achieve what you need to do, you'll have to use a method like SetUpperLHCorner with X and Y parameter. In that method, you can adjust the _lowerRHCorner properties.

    Of course, if you really want to, you can add event handlers on the X and Y properties of Point. But that would be... blech.