Take the 2-minute tour ×

Warning: I'm a C# newb. Besides answering my questions, if you have any tips in general after seeing my code, they are welcome.

Let's say I define a two-dimensional array of size 10x10 in C#:

var arr = new int[10,10];

It is an error to access elements with indices out of the range 0-9. In some applications, (e.g. some games where the 2d-array represents a world) it's necessary to "wrap" the edges of the array. So for example

arr[-1, 0]

would actually refer to the element at arr[9,0].

One approach I've been using is the following class. I didn't subclass System.Array because C# apparently forbids doing so.

Example usage:

var grid = new Grid(10,10);
grid.set(-1, 0, 100); // Set element at (-1,0) to value 100.
grid.at(-1,0); // retrieve element at (-1,0)

The class itself:

class Grid
    public int[,] state;

    public int width { get { return state.GetLength(0); } }
    public int height { get { return state.GetLength(1); } }

    public Grid(int width_init, int height_init)
        state = new int[width_init, height_init];

    int mod(int a, int b)
        if (a >= 0)
            return a % b;
            return (b + a % b) % b;

    int wrap_x(int x) { return mod(x, width); }
    int wrap_y(int y) { return mod(y, height); }

    public int at(int x, int y)
        return state[wrap_x(x), wrap_y(y)];

    public void set(int x, int y, int val)
        state[wrap_x(x), wrap_y(y)] = val;

    // more stuff here...

Question: Is there a game/creative-coding framework out there that provides this sort of class?

Question: Can you think of a simpler mod I can use in the above?

In order to process each element along with the corresponding "x" and "y", I use the following method:

public void each(Action<int, int, int> proc)
            proc(x, y, state[x, y]);

Question: I looked around for a similar method defined on System.Array but I didn't find one. Did I miss it?

Question: In the above, for(int x = 0; x < width; x++) is the common idiom expressing "go from zero up to N by 1". Is there a mechanism which expresses this in C#? I.e. I'd like to write the above as:

width.up_to((x) =>
    height.up_to((y) =>

where up_to would be a method on integers. Is there something like up_to already defined?

Similar to map from Scheme, here's a map method which applies a Func to each element and its corresponding indices. It returns a new Grid.

public Grid map(Func<int, int, int, int> proc)
    var grid = new Grid(width, height);
    each((x, y, val) => grid.state[x, y] = proc(x, y, val));
    return grid;

Question: Let's suppose I setup a subclass class World : Grid which adds additional instance variables. The trouble with the above map is that when called on an instance of World, you get a Grid, not a World. How should I fix this? Is this the wrong approach altogether? Perhaps a better design is to not subclass Grid but to have keep it as an instance variable in World.

Sorry for the long submission. :-)

Update: I asked the question about upto separately and got some good answers.

share|improve this question
You'll have better luck if you make each question a separate... question. –  MPelletier Nov 17 '11 at 4:28
Also, please consider reviewing some of your previous questions and accepting answers where appropriate. –  MPelletier Nov 17 '11 at 4:29
Ideally, you should ask questions one by one. –  Petr Abdulin Nov 17 '11 at 4:33
The more I think about your questions, the more I think some of them would well be received on codereview.stackexchange.com. Just post them one at a time :) –  MPelletier Nov 17 '11 at 4:41
You should make it obvious that your class does wrapping. A name like WrappingGrid might work. /// comments on methods might also work. –  Merlyn Morgan-Graham Nov 17 '11 at 5:20

2 Answers 2

up vote 6 down vote accepted

One thing you can do to facilitate reference to your grid is overload [,]:

public int this[int x, int y]
    get { return state[wrap_x(x), wrap_y(y)]; }
    set { state[wrap_x(x), wrap_y(y)] = value; }

If you find the syntax more suitable, go for it.

Regarding your mod function, the best suggestion I can make is to make those variables (a and b) meaningful. index and maxSize oughta do it.

Other stuff:

  • Your state variable should be private.
  • Unless you absolutely, exclusively need ints, consider using a generic for the type of your state array. Your Grid class becomes Grid<T>.
  • With the bracket [,] overload, you can get rid of your at and set functions.
  • As for your World class, with a simplified Grid, the question to ask is this classic: is or has? IS your World a Grid or does it HAVE a Grid? Only you can answer that, but I'm leaning towards HAS.
  • Consider a Grid constructor which takes a ready-made 2d array as a parameter:


public Grid(int[,] state)
    this.state = state;
  • mod can be made valid for any value (multiple wrap around) with a slight modification.


int mod(int index, int maxSize)
    while (index < 0) index += maxSize;
    return index % maxSize;


  • mod(0,10) => 0
  • mod(1,10) => 1
  • mod(-1,10) => 9
  • mod(10,10) => 0
  • mod(-10,10) => 0
  • mod(11,10) => 1
  • mod(-11,10) => 9
share|improve this answer
I'd considered doing that (overloading [,]) and now that you've encouraged it, I will probably do so. :-) –  dharmatech Nov 17 '11 at 4:46
I made a mistake with the overload, please see the correction. It's actually an overload property :) –  MPelletier Nov 17 '11 at 4:57
Not sure I understand your 3rd bullet point. The set method is used to set a particular location in the grid; how would a constructor help that? –  dharmatech Nov 17 '11 at 5:07
Sorry, that was two items fused into one. It's late where I am... –  MPelletier Nov 17 '11 at 5:14
I added a bullet about your World class, as well as a new mod function. –  MPelletier Nov 17 '11 at 11:51

Just access the array with the modulo % function. For an N by M array use the following.

int x = A[i % N, j % M];

it will do exactly what you need. In your example use arr[-1 % 10, 0 % 10] instead of arr[-1,0]. There is no need for a wrapper function, or additional code!

share|improve this answer
In C# -1 % 10 evaluates to -1, not 9. So the above wouldn't exactly work. :-) –  dharmatech Nov 17 '11 at 6:33
Some languages do produce the "positive mod" with %, but not C#. The other issue (besides negatives) is that new code that refers to the same array will need to carry this strategy, so it has to be added every time. It's a lot of upkeep. –  MPelletier Nov 17 '11 at 11:07
I knew I should have checked it before I posted. Maybe instead of % the wrapping function can be i - (int)(N * Math.Floor((double)i / N)) which wraps the integer i from 0 to N-1. –  ja72 Nov 17 '11 at 16:29

Your Answer


