3

I have the following code:

Point a = new Point(3, 3);

List<Point> points = new List<Point>();

points.Add(a);

a = new Point(50,50);

a.X += 50; 

But say I want the last two lines of code to also affect the value in the list; how would I go about doing this? My guess would be to add pointers to the list? But I think even then "new Point(50,50);" would still not update the list's value?

Thanks

Mohammad Ali Akbari
  • 10,345
  • 11
  • 44
  • 62
Christo
  • 182
  • 3
  • 8
  • I realize that I can access the values directly in the list. But thats not what I want to do. I want to create a debugging window that keeps track of certain variables that I 'register' by adding them to the list. The variables that I want to keep track of are images that should be visible in my debugging window, so its makes no sense to use the debugger. – Christo May 10 '11 at 15:17

2 Answers2

1

No, you don't need pointers. A reference to an object in the .NET world can be thought of as essentially equivalent to a pointer in the world of unmanaged code. Things get a little tricker when you add in the fact that there are both value types and reference types, but in this case, modifying the object, or the object's reference, directly in the array is sufficient.

So, you can do either of the following:

points[0] = new Point(50, 50);

or

points[0].X = 50;
points[0].Y = 50;

(although you should probably get into the habit of treating structures as if they were immutable, so consider the above for example purposes only).

Community
  • 1
  • 1
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • Actually if `points` is a `List` and not an array (as in the question), you can't do: `points[0].X = 50;` because it gives a compilation error: `Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable` – digEmAll May 10 '11 at 15:20
0

You would access the value directly in the list:

points[0] = new Point(50, 50);
Tejs
  • 40,736
  • 10
  • 68
  • 86