Indexing list of Points3d in C# returns error: Index was out of range

Hi All,

I have a list of Boolean items that correlate with lists of x, y, and z values. I try to reference the index of one of the list of points that I am creating and it produces an index range error.

I’m open to anything that you all may think will help!

.gh link:

Your code:

  private void RunScript(double x, double y, double z, bool u, ref object A)
    List<Point3d> pts = new List<Point3d>();
    Point3d tempPt = new Point3d();

    if (u == true) {
      tempPt.X = x;
      tempPt.Y = y;
      tempPt.Z = z;

    } else{

    A = pts;

Your input variables have not been marked as List Access in the input menu, you’ve only specified the type hint, not the access level. So every time the RunScript() method is invoked (once per x, y, z, u quadruplet) you create a brand new list which either is given a single value, or crashes out because you’re trying to access the second element in an empty list at pts[1].

I suspect this is what you’re after:

  private void RunScript(List<double> x, List<double> y, List<double> z, List<bool> u, ref object A)
    // Validate the input data.
    if (x.Count != y.Count) throw new ArgumentException("An equal number of x and y values is required");
    if (x.Count != z.Count) throw new ArgumentException("An equal number of x and z values is required");
    if (x.Count != u.Count) throw new ArgumentException("An equal number of x and u values is required");

    Point3d point = Point3d.Unset;
    List<Point3d> points = new List<Point3d>(u.Count);

    // Iterate over all items.
    for (int i = 0; i < x.Count; i++)
      if (u[i])
        point = new Point3d(x[i], y[i], z[i]);

      if (point.IsValid)

    A = points;

I made the initial point Unset so you don’t start adding bogus points if your u list starts out with false values.

If you don’t want to add any point to the output if u[i] is false, then a small change is needed.

Thanks so much for your help. I’m obviously new to this… I’ll give this a shot as soon as I can

More on…C# List