Sean Farrow
Sean Farrow

Reputation: 59

Resize a c# array

I'm having some trouble resizing a c# 2D array: I have the following code in the private section:

private int[,] _TestArray;

In my properties getter, I'm doing:

if (_TestArray ==null)
_TestArray =new integer[1,1];

Then in a separate function, I'm doing:

_TestArray =new[x,y];

where x and y are two integers that should be the new size of the array. when I then try and add an element to the array, I get an index out of range exception points to the line:

TestArray[x, y] = 5;

I was under the impression that doing a new int[x,y] would resize the array, but clearly not. Can someone please tell me what I've missed? I've looked at the other answers, but non seem to help. Any help apreciated. Cheers Sean.

Upvotes: 2

Views: 411

Answers (1)

Hans Passant
Hans Passant

Reputation: 941455

The last valid element in the array is TestArray[x-1, y-1]. It starts counting at 0. So you probably want to use new int[x+1, y+1] but that's a guess. Do consider using a List<Point> instead, resizing arrays one element at a time is very expensive. List uses a much smarter algorithm and you don't have to copy the elements into the new array yourself.

Upvotes: 6

Related Questions