0

I am trying to construct a map with coordinates -20 to 20 for the x-axis and y axis with C#. At the moment i have defined my ranges(as shown below) and i am using a for each loop to loop through both lists however i can't populate them with anything because it throws an error when i try and reassign the array values back. I would like to draw a map with points. Is my logic wrong?

IEnumerable<int> squares = Enumerable.Range(-20, 20);
IEnumerable<int> cirles = Enumerable.Range(-20, 20); 

int [][] arrays = new int[squares.Count()][cirles.Count()];

            foreach (var shape in squares)
            {

                foreach (var sha in cirles)

\\Construct map

The program throws a type error as it wants me to print out a jagged array to define it like this int [][] arrays = new int[squares.Count()][];

The error is invalid rank or specifier,

ben_fluleck
  • 44
  • 2
  • 8

1 Answers1

1

As mentioned in the comments already you are probably attempting to use the wrong kind of array here. It seems like you'd be better off simply using a 2D array since your dimensions are fixed:

int[,] array = new int[squares.Count(), circles.Count()];

If you want to stick with a jagged array make sure you understand this first: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays.

Jagged arrays cannot be initialized the way you tried it. I suppose the reason for that is that it just wouldn't make an aweful lot of sense. Jagged arrays allow you to have different dimensions for each contained array (which you don't need).

Still, if you want to use a jagged array then use the following code instead for the initialization:

    int[][] arrays = new int[squares.Count()][];
    for (int i = 0; i < arrays.Length; i++)
    {
        arrays[i] = new int[circles.Count()];
    }
dnickless
  • 10,733
  • 1
  • 19
  • 34
  • This is actually very close to answer the problem i have is i want to keep my original coordinates (-20,20) so i can use them to measure distances to points from a custom points class. – ben_fluleck Jun 18 '17 at 06:15
  • If you want to have an array with a negative index... That's not possible. However, you can switch to a custom class instead of a raw int: https://stackoverflow.com/questions/15730346/array-with-negative-indexes. Alternatively, if you don't care a lot about performance you could potentially switch to using a dictionary instead of an array which does support negative keys. – dnickless Jun 18 '17 at 07:02
  • maybe i should be using a Dictionary of Points what do you think? – ben_fluleck Jun 18 '17 at 07:05
  • Maybe, yes. But the "correct" solution depends on the overall problem that you're trying to solve here which I do not know. – dnickless Jun 18 '17 at 10:22