array.Length / Array.Resize()
The Length property gets the number of elements in an array, and the Array.Resize() method changes the size of an array.
Syntax
// Gets the number of elements in the array. array.Length // Resizes the array to newSize elements. Updates the reference to the original array. Array.Resize(ref T[] array, int newSize) // Gets the number of elements in a specific dimension of a multidimensional array. array.GetLength(int dimension)
Member List
| Member | Description |
|---|---|
| Length | Returns the total number of elements in the array. For multidimensional arrays, this is the product of the element counts across all dimensions. |
| Array.Resize(ref T[] array, int newSize) | Changes the length of the array to newSize. When expanding, new elements are initialized to their default value (0 for numbers, null for strings). When shrinking, elements at the end are removed. |
| GetLength(int dimension) | Returns the number of elements in the specified dimension (zero-based). For a one-dimensional array, GetLength(0) returns the same value as Length. |
Sample Code
using System;
// Get the number of elements using Length.
int[] scores = { 85, 92, 78, 95, 60 };
Console.WriteLine(scores.Length); // 5
// Commonly used in a for loop.
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine($"[{i}] {scores[i]} points");
}
// Expand the array using Array.Resize().
string[] team = { "Tanaka", "Suzuki", "Sato" };
Console.WriteLine(team.Length); // 3
Array.Resize(ref team, 5);
team[3] = "Yamada";
team[4] = "Ito";
Console.WriteLine(team.Length); // 5
foreach (string name in team)
{
Console.Write(name + " "); // Tanaka Suzuki Sato Yamada Ito
}
Console.WriteLine();
// Shrink the array using Array.Resize() (elements are removed from the end).
Array.Resize(ref team, 2);
Console.WriteLine(team.Length); // 2
Console.WriteLine(team[0]); // Tanaka
Notes
Arrays in C# have a fixed size once declared. Array.Resize() internally creates a new array and copies the elements, so calling it frequently can impact performance. If the number of elements changes dynamically, consider using List<T> from the start.
For sorting arrays, see Array.Sort() / Array.Reverse(). For searching elements, see Array.IndexOf() / Array.Copy().
If you find any errors or copyright issues, please contact us.