Get Length of a 2D Array in C#

  1. Get Width and Height of a 2D Array With the Array.GetLength() Function in C
  2. Get Width and Height of a 2D Array With the Array.GetUpperBound() Function in C

This tutorial will introduce the methods to get the length (width and height) of a 2D array in C#.

Get Width and Height of a 2D Array With the Array.GetLength() Function in C

The Array.GetLength(x) function gets the number of elements in the x index of a multi-dimensional array in C#. We can pass 0 and 1 in the parameters of the Array.GetLength() function to get the number of elements inside the width and height of a 2D array. The following code example shows us how we can get the width and height of a 2D array with the Array.GetLength() function in C#.

using System;

namespace width_and_height_of_2d_array
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] array2D = new int[5, 10];
            Console.WriteLine(array2D.GetLength(0));
            Console.WriteLine(array2D.GetLength(1));
        }
    }
}

Output:

5
10

In the above code, we got the width and height of the 2D array array2D by passing 0 and 1 as the parameters of the array2D.GetLength() function in C#.

Get Width and Height of a 2D Array With the Array.GetUpperBound() Function in C

The Array.GetUpperBound(x) function gets the index of the last element in the x dimension of a 2D array in C#. We can pass 0 and 1 as parameters of the Array.GetUpperBound() function to find the last index of the dimension 0 and 1 and then add 1 to the output to get the width and height of the 2D array. The following code example shows us how we can find the width and height of a 2D array with the Array.GetUpperBound() function in C#.

using System;

namespace width_and_height_of_2d_array
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] array2D = new int[5, 10];
            Console.WriteLine(array2D.GetUpperBound(0)+1);
            Console.WriteLine(array2D.GetUpperBound(1)+1);
        }
    }
}

Output:

5
10

In the above code, we determined the width and height of the 2D array array2D by passing 0 and 1 as the parameters of the array2D.GetUpperBound() function and adding 1 to the results in C#.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp Array

  • Array of Lists in C#
  • Check if an Array Contains a Value in C#