Most examples when talking about automatically generated properties talk about “simple” value types such as strings. But what if you’d like to access a field of such a value type that is generated automatically in the IL to back up an “automatic property”?
The compiler won’t allow to do this: “Cannot modify the return value of ‘Position’ because it is not a variable”. I understand why we cannot modify this return value, but how would we then access these fields?
Say we have
class A
{
Vector2 Position { get; set; }
public void Foo()
{
Position.X = 10.0f; // Not allowed!
}
}
How do I access and set the field X of the Vector2 instance within class A?
Your problem is that
Vector2is not a reference type; it is a value type. When you access the propertyPositiona copy is returned, so you are attempting to mutate a temporary. In this situation you need to set a completely new value:You could also create a private field in this case and not use an automatic property:
Documentation: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx