-1

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.

Example:

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#?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ren
  • 157
  • 12
  • 1
    "in C# everything are pointers" - not true. Sort of true for reference types (class), but definitely not for value types (struct). How is your `Point` type defined? – Klaus Gütter Dec 23 '21 at 15:49
  • System.Drawing.Point is a structure, is that why? :/ – Ren Dec 23 '21 at 15:51
  • Probably [System.Drawing.Point](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.point) which is a value type. – Klaus Gütter Dec 23 '21 at 15:52
  • 1
    Does this answer your question? [What is the difference between a reference type and value type in c#?](https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c) – Klaus Gütter Dec 23 '21 at 15:53
  • What if a define the class by myself? would it work – Ren Dec 23 '21 at 15:53
  • If you define it as class - yes. – Klaus Gütter Dec 23 '21 at 15:54

2 Answers2

1

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ren
  • 157
  • 12
0

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);
jstnklnr
  • 84
  • 4