Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between modifying a variable and a property

Tags:

c#

.net

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?

like image 702
Øyvind Bråthen Avatar asked Sep 20 '10 07:09

Øyvind Bråthen


People also ask

What is the difference between a property and a function?

Property is the value stored in the hash key, while function is the method stored there. Properties define it, while methods allow it to do things. However, a method is really just a property that can be called through references to functions.

What is difference between field and property in C#?

The difference between field and property in C# is that a field is a variable of any type that is declared directly in the class while property is a member that provides a flexible mechanism to read, write or compute the value of a private field.

What is a property in C#?

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.


2 Answers

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.

like image 140
Darin Dimitrov Avatar answered Oct 18 '22 03:10

Darin Dimitrov


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.

like image 1
Henrik Avatar answered Oct 18 '22 04:10

Henrik