user1610325
user1610325

Reputation: 313

Accessing value types that are automatically generated from properties

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?

Upvotes: 2

Views: 81

Answers (2)

itsme86
itsme86

Reputation: 19526

Vector2 is actually a value type, not a reference type. You'll have to create a new Vector2:

Postion = new Vector2(10.0f, Position.Y);

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124770

Accessing reference types that are automatically generated from properties

Your problem is that Vector2 is not a reference type; it is a value type. When you access the property Position a copy is returned, so you are attempting to mutate a temporary. In this situation you need to set a completely new value:

Position = new Vector2(10.0, Position.Y);

You could also create a private field in this case and not use an automatic property:

class A
{
    Vector2 _position;
    Vector2 Position 
    { 
        get { return _position; } 
        set { _position = value; }
    }

    public void Foo()
    {
        _position.X = 10.0f;  
    }
}

Documentation: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx

Upvotes: 5

Related Questions