Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Obtaining The Length Of Single And Multiple Dimensional Arrays In C#

Jul 16, 2018 • 7 Minute Read

Introduction

In this guide, we are going to take a look at how to obtain the length of a one-dimensional array using the Length keyword and how to retrieve the length of arrays that have multiple dimensions.

Getting the Length of a One-Dimensional Array

In this example, we are creating a simple console application that allocates an array big enough to hold 1000 integers and then writes out what the length of the array is.

      using System;
namespace Pluralsight.ObtainingArrayLength.SingleDimension
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] myIntegers = new int[1000];
      int length = myIntegers.Length;
      Console.WriteLine($"The length of myIntegers is {length}");
    }
  }
}
    

The line that we are most interested in here is where we read myIntegers.Length. When this is compiled, it is converted into the following Intermediate Language (IL) code:

      ldloc.0      // myIntegers
ldlen
conv.i4
stloc.1      // length
    

If we break that down, we find that it's really very simple. The first line of that places the variable myIntegers onto the top of something called the evaluation stack. .NET then uses ldlen to load the length of this array before converting this to an integer using conv.i4. This is finally stored for use using stloc.

In order to understand exactly what C# does, getting a basic understanding of IL is invaluable. This tells us what the compiler produces.

When we build and run our application we should get the following output: The length of myIntegers is 1000

Getting the Length of a Multi-Dimensional Array

Now that we know how to retrieve the length of a single dimension array, let us take a look at how we do the same across multiple dimensions. In this example, we are going to write an application that allocates a grid of 20x30 numbers, and then retrieve and display the length.

      using System;
namespace Pluralsight.ObtainingArrayLength.MultiDimensions
{
  class Program
  {
    static void Main(string[] args)
    {
      int[,] myIntegers = new int[20, 30];
      int length = myIntegers.Length;
      Console.WriteLine($"In two dimensions, the total length is {length}");
    }
  }
}
    

When we build and run this example, we end up with the following being written to the console: In two dimensions, the total length is 600 What we are seeing here is that the length, in this case refers to the length across all dimensions in the array; so, the length here is 20x30. What is more interesting is what happens to the IL. The IL for getting the length in one dimension is trivial but it looks a lot different for multiple dimensions.

      ldloc.0      // myIntegers
callvirt     instance int32 [System.Runtime]System.Array::get_Length()
stloc.1      // length
    

The callvirt line is calling out to Array.get_Length and then putting the resulting value onto the evaluation stack ready for use. This tells us that there is an obvious difference in the behaviour between single and multiple dimension arrays.

We might be tempted to get the length of a particular dimension by trying something like this:

      int length = myIntegers[0].Length;
    

If we typed that in and tried to compile our code, we would find that it fails to compile with the following warning: Wrong number of indices inside []; expected 2

As we know that our array has two dimensions, it might seem reasonable that we could try to get the array of the second dimension like this:

      int length = myIntegers[0,0].Length;
    

If we were to try to compile this code, we would get the following compilation error because myIntegers[0,0] is the value itself: 'int' does not contain a definition for 'Length' and no extension method 'Length' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)

Now that we know that we cannot get the length of an individual dimension in a multi-dimension array using Length, how do we actually obtain the length?

Fortunately for us, .NET provides a useful method called GetLength that accepts the dimension that we want to retrieve.

Dimensions are zero based so getting the first dimension uses 0 and the second dimension uses 1.

Using GetLength our code looks like this:

      using System;
namespace Pluralsight.ObtainingArrayLength.MultiDimensions
{
  class Program
  {
    static void Main(string[] args)
    {
      int[,] myIntegers = new int[20, 30];
      int firstDimension = myIntegers.GetLength(0);
      int secondDimension = myIntegers.GetLength(1);
      Console.WriteLine($"The total length is {firstDimension}x{secondDimension}");
    }
  }
}
    

Now if we compile and run the program, we will get the lengths of each dimension properly printed out: The total length is 20x30

Is the Length Really the Length?

It is perfectly possible to create arrays that don't start at zero. The question is, does Length really return the length of the array or is it just giving us back the value that we put in minus the starting point of the array (something that is called the lower bound)?

Let us suppose that we have an array of five elements with a lower bound of eight.

      Array values = Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 8 });
Console.WriteLine($"Our none zero indexed array has a length of {values.Length}");
    

If we were to run this, the code would still tell us that we had a length of five entries. No matter what the lower bound value of the array, the length will always be the actual length of the array.

Does Length Always Work?

There are two scenarios where we can't get the length using Length. The first case is where we have more items in the array than an integer can hold. In those cases, we can get the length as a long using LongLength and the related GetLongLength methods.

The second case is where we try to get the length of an uninitialized array. When we attempt to call Length on an uninitialized array, the application throws the following exception: System.NullReferenceException: 'Object reference not set to an instance of an object'

Whenever we see this error, it means that we haven't actually instantiated the thing we're looking at. It's good practice to ensure that an object has been created before trying to do anything with it.

Conclusion

We have looked at using Length to get the length of a single dimension array and how to use GetLength to retrieve the length of individual dimensions in a multi-dimension array.

We have briefly discussed retrieving the length of arrays that would be too large to hold in an int using LongLength or GetLongLength.