Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Replace a C# array with a new array of different size
To replace a C# array with a new array of different size, use the Array.Resize method. This method allows you to change the size of an existing array, either expanding or shrinking it while preserving existing elements.
Syntax
Following is the syntax for using Array.Resize −
Array.Resize<T>(ref array, newSize);
Parameters
-
array − The array to resize (passed by reference using
ref) -
newSize − The new size of the array
How It Works
When you resize an array:
-
If the new size is larger, existing elements are preserved and new elements are initialized to their default values
-
If the new size is smaller, elements beyond the new size are removed
-
The original array reference is replaced with the new array
Using Array.Resize to Shrink an Array
Example
using System;
class Program {
static void Main() {
char[] arr = new char[5];
arr[0] = 'J';
arr[1] = 'A';
Console.WriteLine("Original Array Length: " + arr.Length);
// Resize to smaller size
Array.Resize<char>(ref arr, 4);
// Set values for new elements
arr[2] = 'C';
arr[3] = 'K';
Console.WriteLine("Resized Array Length: " + arr.Length);
Console.WriteLine("Updated Array: " + new string(arr));
}
}
The output of the above code is −
Original Array Length: 5 Resized Array Length: 4 Updated Array: JACK
Using Array.Resize to Expand an Array
Example
using System;
class Program {
static void Main() {
int[] numbers = {10, 20, 30};
Console.WriteLine("Original Array: [" + string.Join(", ", numbers) + "]");
Console.WriteLine("Original Length: " + numbers.Length);
// Resize to larger size
Array.Resize<int>(ref numbers, 6);
// Add new elements
numbers[3] = 40;
numbers[4] = 50;
numbers[5] = 60;
Console.WriteLine("Expanded Array: [" + string.Join(", ", numbers) + "]");
Console.WriteLine("New Length: " + numbers.Length);
}
}
The output of the above code is −
Original Array: [10, 20, 30] Original Length: 3 Expanded Array: [10, 20, 30, 40, 50, 60] New Length: 6
Key Points
-
Reference parameter − The array must be passed using
refkeyword -
Performance − Creates a new array internally, so use sparingly for large arrays
-
Type safety − Must specify the generic type parameter
-
Default values − New elements are initialized to default values for the type
Conclusion
The Array.Resize method provides a convenient way to change the size of existing arrays in C#. It preserves existing elements when possible and automatically handles memory allocation, making it ideal for dynamic array size management in applications.
