Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ValueType as property in class

I am a bit confused with a concept of value types as properties in a class.
As far as I understand, when getter is called – a copy of value type is returned.
Let’s have an example:

public struct Point
{
    public int X;
    public int Y;

    public void Set(int x, int y)
    {
        X = x;
        Y = y;
    }
}

public class Test
{
    public Int32 X { get; set; }

    public void SetX(int x) => X = x;

    public Point Point { get; set; }
}

static void Main(string[] args)
{
    var test = new Test();
    test.SetX(10);
    test.Point.Set(20, 30);

    Console.WriteLine(test.X);
    Console.WriteLine($"{test.Point.X} {test.Point.Y}");
}

Point is not modified, since it is a value type, and getter gives us a copy, which makes sense. The thing I don’t understand – why in this case X is modified? It is a value type also. This looks like a contradiction to me.
Please help me to understand what I am missing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Point is not modified, since it is a value type, and getter gives us a copy, which makes sense

Yes, because you get a make changes to local copy of Point returned by auto-property getter.

The thing I don’t understand – why in this case X is modified?

Because you are modifying object containing X not the copy of X. X = x invokes setter (there is no "returns copy" happening here) for auto-property which will write corresponding value to corresponding memory location.

Code for Point simulating this behavior can look for example like:

public void SetPoint(int x, int y) => Point = new Point{X= x, Y =y};

And in both cases the following will work:

test.X = 42;
test.Point = new Point {X = 7, Y = 42}

Demo @sharplab.io

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading