Sunday, 11 August 2013

C# Changing a 2D array to jagged array

C# Changing a 2D array to jagged array

In my code, I've using a 2D multidimensional array to represent a grid
(not always of equal sizes, eg 10x15 or 21x7). After reading about how
jagged arrays are faster and are generally considered better, I decided I
would change my 2D array into a jagged array.
This is how I declared the multidimensional array:
int[,] array = new int[10, 10];
I'm trying to figure out how to declare and then initialise the same
thing, but using jagged arrays.
Edit This code is inside a class, and in the constructor I already have:
class ProceduralGrid
{
private int[][] grid;
private int _columns;
private int _rows;
public ProceduralGrid(int rows, int columns)
{
_rows = rows; //For getters
_columns = columns;
//Create 2D grid
int x, y;
grid = new int[rows][];
for (x = 0; x < grid.Length; x++)
{
grid[x] = new int[10];
}
}
public int GetXY(int rows, int columns)
{
if (rows >= grid.GetUpperBound(0) + 1)
{
throw new ArgumentException("Passed X value (" + rows.ToString() +
") was greater than grid rows (" +
grid.GetUpperBound(0).ToString() + ").");
}
else
{
if (columns >= grid.GetUpperBound(1) + 1)
{
throw new ArgumentException("Passed Y value (" +
columns.ToString() +
") was greater than grid columns (" +
grid.GetUpperBound(1).ToString() + ").");
}
else
{
return grid[rows][columns];
}
}
And in another method I'm simply doing:
Console.WriteLine(grid.GetXY(5, 5).ToString());
However I get "Array does not have that many dimensions" exception when I
try access, for example, grid[5][5].
What am I doing wrong and how should I be doing it?
Thanks

No comments:

Post a Comment