C# Array Resize
To resize an array in C#, call Array.Resize() method and pass the array reference and new size as arguments.
Example
In the following example, we take an array of integers arr
of length 3
, and increase its size to 8
.
Program.cs
</>
Copy
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
int[] arr = {3, 6, 9};
int newSize = 8;
Array.Resize(ref arr, newSize);
foreach (int x in arr) {
Console.WriteLine(x);
}
}
}
}
Output
3
6
9
0
0
0
0
0
Extra elements are added to the array with their default values.
If the new size is less than the original size, then the trialing elements are deleted to match the new size.
In the following example, we take an array of integers arr
of length 3
, and resize it to 2
. Since the new size is less than the original size by one, the last element of this array would be deleted.
Program.cs
</>
Copy
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
int[] arr = {3, 6, 9};
int newSize = 2;
Array.Resize(ref arr, newSize);
foreach (int x in arr) {
Console.WriteLine(x);
}
}
}
}
Output
3
6
Conclusion
In this C# Tutorial, we learned how to resize an array, with examples.