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.

4
  • Aside from the syntax, why would "spieler" be a value for "Breite" of the array? Commented Jan 9, 2014 at 11:04
  • have you tried ARRAY[1D][2D] ? Commented Jan 9, 2014 at 11:05
  • You can't access just a row or column of a 2D array. You need to slice it out int it's own 1D array. Or use jagged array instead of rectangular array. Commented Jan 9, 2014 at 11:05
  • Please consult the documentation. msdn.microsoft.com/en-us/library/2yd9wwz4.aspx You access an array's value like _Spielfeld[0,0]... Commented Jan 9, 2014 at 11:07

2 Answers 2

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.

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.