Grasshopper

algorithmic modeling for Rhino

Why is an item in a point List not behaving like a Point3D ?

Example (inside a C# node):

--

   List<Point3d> pts = new List<Point3d>();
   for(int i = 0; i < per.Count; i++) {
     pts.Add(crv.PointAtNormalizedLength(per[i]));
   }
   Point3d pt = pts[0];
   Vector3d vec = new Vector3d(0, 1, 0);

   pt.Transform(Transform.Translation(vec));

   pts[0].Transform(Transform.Translation(vec));

   A = pts;

   B = pt;

--

The point pt moves but pts[0] item doesn't when I apply the same operation to both of them!

Also I have checked that it works with an Array but not with a List.

Why is this? Can´t I translate a point inside a List directly? 

Thank you!

M.

Views: 342

Replies to This Discussion

Hi M,

Point3d (and Vector3d and Plane and Line and Circle and a lot of other types) are Value Types. It is vital you understand the difference between Value Types (structs) and Reference Types (classes). There are a lot of online resources available for this, for example this one: http://www.albahari.com/valuevsreftypes.aspx

--

David Rutten

david@mcneel.com

Poprad, Slovakia

Ok, now I think that I understand the difference between class and sturct.

You mean that I cannot call struct operations on a class object ?

How do I then call struct methods on a point inside a List?

I always need to pre-store the item in a Point3D?

Thanks a lot !

Miguel

When you're dealing with structs, you must remember that they are copied when you assign them. Have a look at the following:

SomeType A = xxxxxxxxx;

SomeType B = A;

B.SomeProperty = someValue;

In this case, if SomeType is a Reference Type (i.e. a class), then both A and B are pointing to the same instance. Thus, when you modify a property on B, it will also affect A.

If however SomeType is a Value Type, then the B = A statement will create an exact copy of A and store the result in B. This time, changing B will not affect A.

When you access Value Types in a list, you always get a copy of the actual data stored inside the list. Changing this copy will not affect the data in the list. You have to get the point out, modify your local copy, then put the point back into the list. 

You're dealing with arrays, which do allow you to directly modify the elements, but you were creating (and modifying) a copy when you wrote this:

Point3d pt = pts[0];


pt is a copy of pts[0] and therefore changing pt will not affect pts[0].

--

David Rutten

david@mcneel.com

Poprad, Slovakia

RSS

About

Translate

Search

Photos

  • Add Photos
  • View All

Videos

  • Add Videos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service