0

Following situation: I have a Array which got 2 dimension. No i want to access the second dimension. How can i achieve this goal?

Here my code to clarify my problem:

private static int[,] _Spielfeld = new int[_Hoehe, _Breite];

    private static bool IstGewonnen(int spieler)
    {
        bool istGewonnen = false;

        for (int zaehler = 0; zaehler < _Spielfeld.GetLength(0); zaehler++)
        {
            //Here i cant understand why compiler doesnt allow
            //Want to give the second dimension on the Method
            istGewonnen = ZeileSpalteAufGewinnPruefen(_Spielfeld[zaehler] ,spieler);
        }

        return istGewonnen;
    }

//This method want to become an Array
private static bool ZeileSpalteAufGewinnPruefen(int[] zeileSpalte, int spieler)
{ 
  //Some further code
}

The compiler is saying: "Argument from type int[,] is not assignable to argument of type int[]. In Java it is working as i expected. Thanks in advance.

Sebi
  • 3,879
  • 2
  • 35
  • 62

2 Answers2

3

Define your array as a jagged array (array of arrays):

private static int[][] _Spielfeld = new int[10][];

Then loop through the first dimension and initialize.

for (int i = 0; i < _Spielfeld.Length; i++)
{
    _Spielfeld[i] = new int[20];
}

Then the rest of your code will compile OK.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
2

C# allows two different offers two flavors of multidimensional arrays which, although they look quite similar, handle quite differently in practice.

What you have there is a true multidimensional array, from which you cannot automatically extract a slice. That would be possible (as in Java) if you had a jagged array instead.

If the choice of having a multidimensional array is deliberate and mandatory then you will have to extract slices manually; for example see this question.

If the choice between jagged and multidimensional is open then you can also consider switching to a jagged array and getting the option of slicing for free.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806