How to Get Length of a 2D Array in C#

Muhammad Maisam Abbas Feb 16, 2024
  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#
How to Get Length of a 2D Array 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 got 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.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Csharp Array