Home > Software engineering >  how to declare a bidimensional array
how to declare a bidimensional array

Time:12-11

I have this code:

var test = new string[3, 2];
            for (int i=0; i<3; i  )
            {
                for (int h=0; h<2; h  )
                {
                    test[i, h] = "DataRows: "   i.ToString()   " "   h.ToString();
                }
            }

but when I try to see what's inside of test I see this

quick watch

If I try to see what is in any item of the array I get an error:

error in item in array

Can someone explain to me what I am doing wrong and what is the correct way?

Visual Studio 2022, Blazor Webassembly, .NET6.0

Thanks

CodePudding user response:

C# supports multidimensional arrays as well as the so-called jagged arrays

The following sample code shows how to use them both

using System;

namespace Test
{
    class Program
    {
        static void Main()
        {
            // Multidimensional array  

            string[,] multidimensionalArray = { { "alpha", "beta", "gamma" }, { "delta", "epsilon", "zeta" } };

            for (int x = 0; x < multidimensionalArray.GetLength(0); x  )
            {
                for (int y = 0; y < multidimensionalArray.GetLength(1); y  )
                {
                    Console.WriteLine(multidimensionalArray[x, y]);
                }
            }

            // Jagged array 

            string[][] jaggedArray = { new string[] { "alpha", "beta", "gamma" }, new string[] { "delta", "epsilon", "zeta" } };

            for (int x = 0; x < jaggedArray.Length; x  )
            {
                for (int y = 0; y < jaggedArray[x].Length; y  )
                {
                    Console.WriteLine(jaggedArray[x][y]);
                }
            }

        }

    }
}

For more information, please see

  • console debugging screenshot

  • Related