1

I am trying to change a struct values (located in class A) from another class (class B per say) I wrote a method to get the struct (the method is located in class A) but all I get is a shallow copy (the values do not really change...) any help?

1 Answer 1

3

Yes, that's what happens with structs. You need to make the changes locally, then shallow copy back again. For example:

public class Foo
{
    public Point Location { get; set; }
}

public class Bar
{
    private Foo foo = new Foo();

    public void MoveFoo()
    {
        Point location = foo.Location;
        location.X += 10;
        location.Y += 20;
        // Copy it back
        foo.Location = location;
    }
}

Personally I try to avoid making structs mutable in the first place - but will often given them what I call "pseudo-mutator" methods which return a new value with appropriate changes. So for example, for a Point struct I might have a method like this:

public Point TranslatedBy(int dx, int dy)
{
    return new Point(x + dx, y + dy);
}

Then the MoveFoo method above would be:

foo.Location = foo.Location.TranslatedBy(10, 20);
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up using a class instead..It solved the pointers problem plus I might need to add some methods inside so a class will be more appropriate...TNX anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.