How to Resize Array in C#: Syntax and Examples
In C#, you can resize an array using the
Array.Resize<T> method, which changes the size of the array while preserving existing elements. This method creates a new array internally and assigns it back to your array variable.Syntax
The syntax to resize an array in C# uses the Array.Resize<T> method where T is the type of the array elements.
ref T[] array: The array variable to resize, passed by reference.int newSize: The new size for the array.
This method modifies the original array variable to point to a new array with the specified size.
csharp
Array.Resize<T>(ref T[] array, int newSize);Example
This example shows how to resize an integer array from size 3 to size 5, preserving the existing elements and adding default values for new positions.
csharp
using System; class Program { static void Main() { int[] numbers = { 1, 2, 3 }; Console.WriteLine("Original array length: " + numbers.Length); // Resize the array to length 5 Array.Resize(ref numbers, 5); Console.WriteLine("Resized array length: " + numbers.Length); Console.WriteLine("Array contents:"); foreach (int num in numbers) { Console.WriteLine(num); } } }
Output
Original array length: 3
Resized array length: 5
Array contents:
1
2
3
0
0
Common Pitfalls
Common mistakes when resizing arrays include:
- Not passing the array variable by
ref, which means the original array won't be updated. - Assuming the array resizes in place; actually, a new array is created and assigned.
- Forgetting that new elements are initialized with default values (e.g., 0 for int, null for reference types).
csharp
using System; class Program { static void Main() { int[] numbers = { 1, 2, 3 }; // Wrong: missing ref keyword - this won't resize the original array // Array.Resize(numbers, 5); // This causes a compile error // Correct way: Array.Resize(ref numbers, 5); Console.WriteLine("Resized length: " + numbers.Length); } }
Output
Resized length: 5
Quick Reference
Array.Resize<T> Cheat Sheet:
| Action | Syntax | Notes |
|---|---|---|
| Resize array | Array.Resize(ref array, newSize); | Resizes array preserving elements, new elements get default values. |
| Increase size | Array.Resize(ref array, largerSize); | Adds default values at the end. |
| Decrease size | Array.Resize(ref array, smallerSize); | Truncates elements beyond new size. |
| Pass by reference | ref keyword is required | Without ref, array won't be updated. |
Key Takeaways
Use Array.Resize(ref array, newSize) to resize arrays in C# safely.
Always pass the array variable with the ref keyword to update it.
Resizing creates a new array; existing elements are copied, new ones get default values.
You can both increase and decrease the array size with Array.Resize.
For dynamic collections, consider using List instead of arrays.