Search code examples
c#gettervalue-typereference-type

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


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