Search code examples
c#copydeep-copyshallow-copy

in c# code why below copy didn't work as reference copy?


Below c# code I run in Visual Studio 2019 Mac, I am a little surprise for the result:

using System;

namespace Test
{
    public struct Point
    {
        public int x;
        private int y;
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Point p1 = new Point(100, 100);
            Point p2;
            p2 = p1;
            p1.x = 200;
            Console.WriteLine("p1.x is {0},p2.x is {1} ", p1.x, p2.x);
            // I think here should Output: p1.x is 200, p2.x is 200
            // But the actual output is: p1.x is 200, p2.x is 100, why? is it a reference copy?
            // p1 and p2 should share the same reference, right?
        }

    }
}

Actually when I read C# instruction, it explained that such code should output: p1.x is 200,p2.x is 200 because p2 and p1 share the same pointer to point to ONE address in heap, right? while when I try to test above code in VS2019 Mac. it's output is: p1.x is 200,p2.x is 100 which confused me so much? Is it a shallow copy or deep copy? Can somebody please explain why p2.x is still 100, when p1.x already changed to 200? Thanks a lot.


Solution

  • Your Point is a struct. When you assigned p2 to p1, p2 became a copy. I think you might want to read up a bit more on value types versus reference types.