Search code examples
c#arrayspoints

Create a empty array of points


I'm trying to create a empty array of points, for this i'm using the following

    Point[] listapontos = new[]; //should create a empty point array for later use but doesn't.
               Point ponto = new Point(); //a no coordinates point for later use
               for (int i = 1; i <= 100; i++) //cycle that would create 100 points, with X and Y coordinates
               {
                   ponto.X = i * 2 + 20;
                   ponto.Y = 20;
                   listapontos[i] = ponto;
               }

I'm having some trouble, because I can't create a empty array of points. I could create a empty array of strings using a list, but since i will need two elements, a list isn't useful here.

Any hints? (hints for the problem are also welcome)


Solution

  • // should create a empty point array for later use but doesn't.

    No, what you've specified just isn't valid syntax. If you want an empty array, you could use any of:

    Point[] listapontos = new Point[0];
    Point[] listapontos = new Point[] {};
    Point[] listapontos = {};
    

    However, then you've got an array with 0 elements, so this statement:

    listapontos[i] = ponto;
    

    ... will then throw an exception. It sounds like you should either use a List<Point>, or create an array of size 101:

    Point[] listapontos = new Point[101];
    

    (Or create an array of size 100, and change the indexes you use - currently you're not assigning anything to index 0.)

    It's important to understand that in .NET, an array object doesn't change its size after creation. That's why it's often convenient to use List<T> instead, which wraps an array, "resizing" (by creating a new array and copying values) when it needs to.