2

I'm having a char array :

public static char[] boardposition = new char[9];

I want to reset the array , my written function for this is:

public static void Reset()
{            
     Array.Clear(boardposition,9, boardposition.Length);
}

When I call the Reset() I get an exception of type IndexOutOfRangeException.

I hope you guys can help me out.

braX
  • 11,506
  • 5
  • 20
  • 33
Elvira
  • 1,410
  • 5
  • 23
  • 50
  • possible duplicate of [What is an "index out of range" exception, and how do I fix it?](http://stackoverflow.com/questions/24812679/what-is-an-index-out-of-range-exception-and-how-do-i-fix-it) – Omar Apr 16 '15 at 10:23
  • @Fuex I disagree re: this question being duplicate; Elvira wants to know how to perform Array.Clear, and the exception is entirely coincidental. – Liz Apr 16 '15 at 17:07

3 Answers3

7

You are passing 9 as starting index wich isn't a valid index for your array. Make the call like this Array.Clear(boardposition,0, boardposition.Length);

3

The method Array.Clear takes the following parameters:

  • Array array - the Array on which the Clear will be performed.
  • int index - the starting position from which to start clearing
  • int length - the number of elements which should be cleared.

A bit of test coding covereth a multitude of sins... including sins of misleading or unhelpful documentation.

In your case, the index caused the exception: the last valid position would be Length - 1.

As to the solution: if you intend to clear the entire array while retaining bot initial pointer and array size, the answer is:

Array.Clear(boardposition, 0, boardposition.Length );

If, however, you have no issues with changing the address of the Array, just assign it a new Array with same length; the end result would still be a zeroed Array of length 9:

boardposition = new char[9];

Edit: the best use scenario depends entirely on how boardposition is used later on in the program.

Liz
  • 378
  • 3
  • 19
0

An IndexOutOfRangeException can be raised if the index is smaller than the lower bound of the array, the length is less than zero or if the sum of index and length is greater than the size of array.

In your case the sum of the index and length is (boardposition.Length+9) which exceeds the length of the array and therefore an exception is raised. You need to change your code to:

public static void Reset()
{            
    Array.Clear(boardposition,0, 9);
}
Alex
  • 21,273
  • 10
  • 61
  • 73
  • 1
    If you check boardposition declaration `public static char[] boardposition = new char[9];` so this function won't do nothing – alessio bortolato Apr 16 '15 at 10:08
  • @alessio-bortolato Why won't it work? You can reassign statics whenerver you feel like it... it's not like they're const or readonly. – Liz Apr 17 '15 at 06:01
  • @Liz My comment was about is initial answer in wich he said `Array.Clear(boardposition,9, boardposition.Length-9);` – alessio bortolato Apr 17 '15 at 07:05