Home > Blockchain >  c# WindowsForm Point pointer value not changing
c# WindowsForm Point pointer value not changing

Time:12-24

As my teacher always told me: "in C# everything are pointers",

I am currently on a project where I use Windows Forms and the Point class that goes with it,

exemple:

            Point a = new Point(200, 200);
            Point b = a;
            a.X = 100;
            Console.WriteLine(b.X);

As 'a' is a pointer, when setting 'b' to 'a' and then changing 'a.X' value, b.X value should change too right? But I still get 200 as a result.

I would like it to be 100 (keeping a link between them), is there any way to do this in C#?

Thanks

CodePudding user response:

For people that have the same problem:

defined as a class it would work, but not as a structure, overrighting the structure with an equivalent class do the trick.

thanks Klaus for the link it does answer my question and way more so I wanted to clarifie it in a shorter answer

CodePudding user response:

As you've found out, value types are copied by value and not by reference.

However if you want an actual reference to this object you could easily just do it like this.

Point a = new Point(200, 200);
ref Point b = ref a;
a.X = 100;
Console.WriteLine(b.X);
  • Related