Jump to content
  • Advertisement
Sign in to follow this  
Estauns

[.net] Property Struct Weirdness..

This topic is 4869 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Why can you not modify a struct's value's when returning it from a property? This works: int x = picture.Position.X; This doesn't: picture.Position.X = 5; It says: Cannot modify the return value of 'Picture.Position' because it is not a variable I define it like this: public Point Position { get { return _position; } set { _position = value; } } I just don't see the point of doing something like picture.Position = new Point(<whatever I want>, picture.Position.Y); If I make a new class called Point with all of the same things, it works just fine. So it's because its a struct its not working. Why did they make it like this? IT doesn't seem to amke any sense.

Share this post


Link to post
Share on other sites
Advertisement
The problem is you're trying to modify a temporary. When you return a struct you get a copy, not a reference to the original. What you can do, is assign the return value to a temporary variable, modify the variable and then assign it back to the property.

Share this post


Link to post
Share on other sites
Quote:
Original post by Estauns
Why did they make it like this? IT doesn't seem to amke any sense.

I was actually relieved that they DID make it this way. It made sure that no one was going to use Get() to access and change my property, without the logic of Set() being run. Thats important when I need to resize all of my resources on Size Set().

Share this post


Link to post
Share on other sites
This illustrates why it can be bad to have mutating member functions on structs. Imagine you have a vector(the geometric kind) struct with a normalize function. Now, if you invoke that function through a property - ie, model.Direction.Normalize(), you end up calling the function on the temporary - and the original is not affected at all.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!