1

I'm working around an array, in which i wanna add some of its values. At some points, for this do be done with just one calculation, it will ask for an index outside the array.

Is there a way to say, 'if an index is outside the array, assume the value to be 0' ?

Something a bit like this:

                   try
                   {

                   grid[x,y] = grid[x-1,y] + grid[x-1,y-1];
                   //This is simplified 

                   x++;

                   }

                   catch (IndexOutOfRangeException)
                   {                           
                           grid[x - 1, y - 1] = 0;
                   }
4
  • 3
    Arrays are fixed size, so hopefully you don't have to make guesses about legal indexes. It is much better to perform the check and make adjustments as necessary to the index than catching exceptions. Commented Aug 11, 2014 at 15:27
  • look up ternary operator! Like grid[x <= legalSize? x : 0] Commented Aug 11, 2014 at 15:27
  • With single dimensional arrays you can simply use ElementAtOrDefault which already returns your desired value. Commented Aug 11, 2014 at 15:33
  • @TaW It should be x < legalSize, and you may want to add 0 <= x too. Commented Aug 11, 2014 at 15:35

1 Answer 1

4

Assuming for simplicity that you have an integer array, you may consider extension method like the following:

static class ArrayExtension
{
    static int SafeGetAt(this int[,] a, int i, int j)
    {
        if(i < 0 || i >= a.GetLength(0) || j < 0 || j >= a.GetLength(1))
            return 0;
        return a[i, j];
    }
}

and then access array elements as

grid.SafeGetAt(x, y);

An alternative approach could be to make a wrapper class which accesses the array internally and inplements an indexer. In this case you may keep using [,]-syntax to access elements.


I would not suggest using exceptions, which are quite slow and should be avoided in regular application workflow.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.