Øyvind Bråthen
Øyvind Bråthen

Reputation: 60734

Difference between modifying a variable and a property

There is probably a quite logical explanation to this, but I have a question.

Let's say I have a variable of type Rectangle called _rect. I can now say _rect.X = 50; without any problems.

Now I have a class with a property called Rect that exposes the internal variable _rect.

Then, if I try to write Rect.X = 50; I get the following compilation error:

Cannot modify the return value of 'TestClass.Rect' because it is not a variable.

I can write Rect = new Rectangle( 50, Rect.Y, Rect.Width, Rect.Height) like for a immutable type, but for non-immutable types, are there any other way of doing this?

I want to use auto-properties for this rectangle field, but it's really annoying not being able to modify it inside the class itself.

Are there any way short of making a backing field and dropping the auto-property?

Upvotes: 8

Views: 1060

Answers (4)

explorer
explorer

Reputation: 12110

  class RectangleWithoutFields 
  {
     // just autoproperties, no fields

     public int X { get; set; }

     public int Y { get; set;}


     public RectangleWithoutFields()
     {
         X = 0;

         Y = 0; 
     }

     public void ChangeProperties(int x, int y)

     {
         X = x;

         Y = y;
     }
 }

Upvotes: 0

Henrik
Henrik

Reputation: 23324

Accessing the property is really a function call which returns a copy of the value type. Rect.X = 50; would only modify this temporary copy, not the backing field itself.

When the property is not auto-implemented, you could create an additional property RectX, which can be used to get and set the X property of the rectangle.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

The reason for this error is because Rectangle is a value type (struct) in contrast to reference types (classes). You cannot modify the X property because when you use the Rect property getter a new value for the rectangle is returned (the getter is a function). If it was a reference type you are manipulating the pointer and this would be possible.

This is an important aspect of value vs reference types to be aware of.

Upvotes: 10

Related Questions