Christo
Christo

Reputation: 182

Add references to objects to a list

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

Upvotes: 3

Views: 3480

Answers (2)

Cody Gray
Cody Gray

Reputation: 244712

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

Upvotes: 1

Tejs
Tejs

Reputation: 41236

You would access the value directly in the list:

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

Upvotes: 0

Related Questions