Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add references to objects to a list

Tags:

c#

list

pointers

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

like image 673
Christo Avatar asked Nov 27 '25 06:11

Christo


1 Answers

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).

like image 145
Cody Gray Avatar answered Nov 29 '25 21:11

Cody Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!