Click to See Complete Forum and Search --> : Properties for attributes of complex objects
Stonehead
August 3rd, 2009, 06:20 PM
Can someone tell me how to make a property for an attribute of an object?
To be more precise, I want to make properties for X and Y attributes of Vector2 object.
How do I do that?
Vector2 Position {
set {...}
get {...}
}
... works only on the whole object. I want to do the same with its attributes: X and Y.
Thanks! ^^
BigEd781
August 3rd, 2009, 06:26 PM
Just wrap them each in their own property. The reason it does not work for x and y is because Vector2 is a value type, so you are returning a copy when you call foo.Position.X. Just make a new property and set the private member yourself.
Vector2 Position { get; set; }
int PositionX
{
get { return Position.X; }
set { Position = new Vector2( value, Position.Y ); }
}
// same for y
Arjay
August 3rd, 2009, 06:28 PM
If you return the whole Vector object, can't you access its Position members?
BigEd781
August 3rd, 2009, 06:35 PM
If you return the whole Vector object, can't you access its Position members?
He wants to set them though. Since Vector2 is a value type (like Point), you can expose it as a property and then, from calling code, set only a member of the object.
int x = Position.X; // works fine of course
x +=1;
Position.X = x; // doesn't work, a copy is returned
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.