Hi, not sure if the title is correct but I think that's what I mean.

I have the following code:

//Box the shape is contained in
        protected Rectangle container;

        /// <summary>
        /// Gets or sets the value for position
        /// </summary>
        public Point Position
        {
            get { return container.Location; }
            set { container.Location = value; }
        }

And then later in a derived class I have the function

public override void move(Point destination)
        {
            Position.X += destination.X;
            Position.Y += destination.Y;
        }

When I compile this it says Error 1 Cannot modify the return value of 'TextVisualiser.Drawing.basicShapes.Position' because it is not a variable . What does this mean? Do I have to have a variable with the same name as the property?

Thanks for any and all help.

Andrew.

Dani AI

Generated

The compiler is complaining because Position returns a Point (a value type). A property call returns a copy, not a variable you can modify in-place, so attempts to mutate a field of that returned struct are disallowed.

was right to suggest working on a local copy, but the missing step is writing that modified copy back to the property (or mutating the backing field). One concise fix is to compute a new Point and assign it back:

Position = new Point(Position.X + destination.X, Position.Y + destination.Y);

An alternative that avoids creating a new Point is to change the backing rectangle directly (you already have container):

container.Offset(destination);

Design notes: exposing mutable structs via properties can be surprising. Safer patterns are (a) provide a method like MoveBy(Point delta) that updates the backing field, or (b) keep the property immutable and require setters to replace the whole value. Converting Point to a reference type just to avoid the copy semantics is usually a bad idea because it changes semantics and can introduce other bugs.

Summary for : you do not need a variable with the same name as the property. You must either create a modified value and assign it back to the property (or mutate the backing field), or expose an API that performs the mutation on the underlying data.

Hi,

Do you override any thing about the definition of property called Position ? If not then your problem is you try to use += variable on a value type member of position but position it self is neither value, nor reference type it is just a property with accessor functions defined. Try that instead :

public override void move(Point destination)
{
    Point p = Position;
    p.X += destination.X;
    p.Y += destination.Y;
}

Loren Soth

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.