#1,016 – Retrieving the Length of an Array

You can use the Length property of an array to get the number of elements in the array.

For a one- or multi-dimensional arrays, the length is always the total number of elements.  For a jagged array (array of arrays), the length is the number of elements in the outer dimension.

            int[] someNumbers = { 5, 16, 12, 38, 78, 63 };
            // Length = 6
            Console.WriteLine(someNumbers.Length);

            int[,] twoDimensional = { { 3, 2, 1 }, { 1, 2, 3 }, { 4, 6, 8 } };
            // Length = 9
            Console.WriteLine(twoDimensional.Length);

            int[][] jagged = new int[3][] {
                new int[] { 1, 2, 3 },
                new int[] { 4, 8 },
                new int[] { 10, 20, 30, 40 } };
            // Length = 3
            Console.WriteLine(jagged.Length);

1016-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment