0
public class TouchableArea  {
public Rect rect;   

public Rect Rect{
    get{return rect;}
    set{rect = value;}
}
}

Above is my class. Rect is a struct and has a function Set to set new value. When I use the property to set a new value to rect nothing happens, but when I use the rect directly everything is fine.

TouchableArea t = new TouchableArea();
t.Rect.Set(newValue);//Through property, nothing happens
t.rect.Set(newValue);//Directly access, it works.

Does this mean it's illegal to call a function through a property?

yoozer8
  • 7,361
  • 7
  • 58
  • 93
Matrix Bai
  • 1,097
  • 3
  • 11
  • 20

2 Answers2

4

When you change the property, IL calls a method that returns you the object. Since it's a "value" object, t.Rect doesn't return you object rect, it returns a copy. So, you are modifying a copy of rect.

Andrey
  • 20,487
  • 26
  • 108
  • 176
1

On a fundamental level, modifying a property of the struct won't work, as structs are value types, value types when assigned would just receive copies. Hence, cannot cascade the changes back to the original.

Though the problem can be rationalized as such. Some compiler writers can perform magic on our behalf. This is the sort of thing which Miguel de Icaza is trying to propose to C#

http://tirania.org/blog/archive/2012/Apr-11.html

If VB.NET can have a ByRef on properties (there was no rationalization done by their language designers why it could not be feasible, they just code around it, and it feels like magic; there could be some sort of leaky abstraction that could arise by facilitating so, but to them, the advantages far outweighs the disadvantages so to speak); copied struct's properties could be modified too, if they will accept his proposal

Michael Buen
  • 38,643
  • 9
  • 94
  • 118