Still a little confused about changing structs

Started by
2 comments, last by Gl2eenDl2agon 9 years, 3 months ago

Hi,

I'm still a bit confused about structs being copied when they are modified. I have a ray class, with two vectors ...


    public class Ray
    {
        public Vector3 Origin { get; set; }
        public Vector3 Direction { get; set; }

        public Ray(Vector3 origin, Vector3 direction)
        {
            Origin = origin;

            direction.Normalize();
            Direction = direction;

            /* this doesn't work*/
            //Direction = direction;
            //Direction.Normalize();
        }

What I don't get is why direction.Normalize() modifies direction, but Direction.Normalize() doesn't modify Direction.

Edit : My running theory, is that after Normalize is called, both direction and Direction are copies local to the constructor, and in the first case, it is actually assigned to the global, but in the second, it is left unused.

Advertisement
It's because getting a struct from a property makes a copy (as a temporary variable, in the case of your commented-out code, which is immediately discarded after Normalize is called on it). Modifying the copy doesn't affect the original.

Options you can use (pick whichever is more appropriate):

- Make modifications in a local variable then assign the result to the property (this is what you're doing in your current version of code).
- Change the properties to fields (remove the get and set), which will allow the commented out code to function properly because no temporaries will be made. This is slightly more efficient due to less copying, but doesn't work if your properties need to be exposed by an interface.

Thanks,

All the discussions that I've read about the problem often center around (im)mutability, but don't raise the difference between properties and fields. I didn't know that properties return copies (of structs). It seems kind of important to know :$

I may be naive by saying this, but it seems wrong that I should even be allowed to create a copy and not use it, without a warning that it's never used.


I may be naive by saying this, but it seems wrong that I should even be allowed to create a copy and not use it, without a warning that it's never used.

But you did use it. You normalized it.

You just forgot what "pass by copy" vs "pass by reference" means.

If I cloned your body and then tasered your clone you would not feel it. (two distinct people- ie pass by copy)

If I used some hackery of quantum physics and made it so you could be in two places at the same time and still be one person (a reference or pointer) and I tasered one of your appearances, you would feel it.

This topic is closed to new replies.

Advertisement