Back to Blog
C#

C# Array Length: Property, Pitfalls, and Performance

c# array length: Learn how to use the Length property on C# arrays, handle multi-dimensional and jagged arrays, avoid common mistakes, and understand performance impli...

C#ArraysLength PropertyCollectionsPerformance
Illustration of a C# array with its Length property highlighted, showing the number of elements.

c# array length requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

In C#, every array exposes a Length property that returns the total number of elements in the array. This is the primary way to get the array length, and it works across all array types. The property is read-only and returns an int value, so it cannot be assigned to. Understanding how Length behaves for different array shapes is essential for writing correct loops, bounds checks, and collection conversions.

The Length Property on Single-Dimensional Arrays

For a standard one-dimensional array, Length gives the exact number of elements. The array indexes run from 0 to Length - 1, which is the basis for most iteration patterns.

int[] numbers = new int[] { 10, 20, 30, 40 }; int count = numbers.Length; // 4 for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); }

The Length property is a direct field read from the array's internal metadata, so accessing it is an O(1) operation. It does not iterate or compute anything. This makes it safe to call repeatedly in loop conditions without a performance penalty.

An empty array has Length equal to 0. This is a valid state, and checking array.Length == 0 is a common way to test for emptiness before processing.

Length on Multi-Dimensional and Jagged Arrays

C# supports two kinds of multi-dimensional arrays: rectangular arrays and jagged arrays. The Length property behaves differently for each.

A rectangular array is declared with a single type and fixed dimensions, such as int[,]. Its Length property returns the total number of elements across all dimensions, not the size of a single dimension. For example, a 3 by 4 array has Length equal to 12.

int[,] grid = new int[3, 4]; int totalElements = grid.Length; // 12 int rows = grid.GetLength(0); // 3 int cols = grid.GetLength(1); // 4

To get the size of a specific dimension, use the GetLength(int dimension) method. The dimension argument is zero-based, so GetLength(0) returns the first dimension's size.

A jagged array is an array of arrays, such as int[][]. Its Length property returns the number of sub-arrays in the outer array, not the total element count. Each sub-array can have its own length.

int[][] jagged = new int[3][]; jagged[0] = new int[] { 1, 2 }; jagged[1] = new int[] { 3, 4, 5 }; jagged[2] = new int[] { 6 }; int outerLength = jagged.Length; // 3 int firstInnerLength = jagged[0].Length; // 2

This distinction is easy to miss. If you assume Length on a jagged array returns the total element count, you will get the outer count instead. For a total count across all sub-arrays, you must sum each sub-array's Length.

Comparing Array Length with List Count

Arrays are fixed-size, while List<T> is dynamically resizable. The List<T> class exposes a Count property, not Length. The Count property also returns the number of elements, but it is backed by a field that is updated as items are added or removed.

List<int> list = new List<int> { 1, 2, 3 }; int listCount = list.Count; // 3

There is also a LINQ extension method Count() that works on any IEnumerable<T>. For arrays and lists, calling Count() will often use the Count property internally, but it adds a method call and can be slower if the sequence is not a collection. Prefer Length on arrays and Count on lists to avoid unnecessary overhead.

Collection TypeMember to UseReturn TypeMeaning
ArrayLengthintTotal elements in the array
List<T>CountintNumber of elements currently in the list
IEnumerable<T>Count()intCounts elements by enumeration (LINQ)

The Count property on a list is O(1), but it tracks a separate counter. Arrays store the length directly in their metadata, so Length is equally efficient. When converting between arrays and lists, you can use the appropriate property to get the size without changing the underlying data structure.

Common Pitfalls When Using Array Length

One of the most frequent mistakes is using Length as the upper bound in a loop without accounting for zero-based indexing. The correct loop condition is i < array.Length, not i <= array.Length. The latter causes an IndexOutOfRangeException on the last iteration.

int[] data = new int[] { 5, 6, 7 }; // Correct for (int i = 0; i < data.Length; i++) { Console.WriteLine(data[i]); } // Incorrect: throws IndexOutOfRangeException for (int i = 0; i <= data.Length; i++) { Console.WriteLine(data[i]); }

Another pitfall is assuming that Length reflects the number of elements that have been assigned. In C#, an array is always initialized with default values for its element type. A newly created int[5] has five elements, all set to 0. Length returns 5 regardless of how many elements you have explicitly set. This is different from a List<T>, where Count reflects the number of items you have added.

For multi-dimensional arrays, using Length when you need a specific dimension size leads to incorrect bounds. Always use GetLength for dimension-specific checks. For jagged arrays, remember that Length only gives the outer count; inner arrays must be accessed individually.

Performance and Memory Characteristics of Length

Accessing Length is a constant-time operation because the value is stored as part of the array object's header in memory. The runtime does not need to iterate or calculate anything. This is true for all array types, including multi-dimensional and jagged arrays.

Because Length is a property that reads a stored field, calling it in a loop condition does not add meaningful overhead. The JIT compiler can often hoist the property access out of the loop if it can prove the array reference does not change. In practice, you do not need to cache Length in a local variable for performance reasons, although doing so can make the intent clearer.

int[] items = GetItems(); int len = items.Length; // Optional local copy for (int i = 0; i < len; i++) { Process(items[i]); }

The memory footprint of an array includes the length value itself, which is stored once per array instance. For large arrays, this is negligible compared to the element data. However, if you create many small arrays, the per-object overhead can become noticeable. In such cases, consider using Span<T> or Memory<T> to avoid separate array allocations, but note that Span<T> does not have a Length property; it uses Length as well, but on a ref struct that wraps a managed or native buffer.

Choosing Between Array and Other Collection Types Based on Length

Arrays are the right choice when the number of elements is fixed at creation time and you need direct indexed access. The Length property gives you a stable count that cannot change, which simplifies reasoning about bounds.

If you need to add or remove elements dynamically, a List<T> is more appropriate. Its Count property reflects the current number of elements, and it handles resizing internally. Converting an array to a list with new List<T>(array) copies the elements, and the list's Count will match the array's Length at that moment.

For high-performance scenarios where you need to pass a contiguous region of memory without allocating, Span<T> is a modern alternative. It exposes a Length property as well, but it is not a class; it is a ref struct that can point to an array, a native buffer, or a stack allocation. The semantics are similar, but you must be aware of its stack-only nature.

int[] buffer = new int[100]; Span<int> span = buffer.AsSpan(); int spanLength = span.Length; // 100

When you need to return a collection from a method, consider whether the caller should be able to modify the size. Returning an array signals that the size is fixed. Returning a List<T> allows the caller to add or remove items. The choice affects how the consumer interprets the Length or Count property.

For multi-dimensional data, rectangular arrays are more memory-efficient because they store elements in a single block. Jagged arrays allow each row to have a different length, which can be useful for sparse data, but they require more careful length handling. Use GetLength for rectangular arrays and access each inner array's Length for jagged arrays.

Ultimately, the Length property is a fundamental part of array usage in C#. Understanding its behavior across different array shapes and comparing it with collection alternatives helps you write code that is correct, efficient, and maintainable.

c# array length: Practical Usage and Code Examples | RYUSLOG DEV