C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Step 1: We initialize an array of characters. It has 4 elements, and we assign them all to char values.
Char ArrayStep 2: We invoke Array.Resize with argument of 2. This call changes an array of 4 elements to one with 2 elements.
So: We reduce the size of the array by 2 elements. Array.Resize can expand, or shrink an array's size.
C# program that uses Array.Resize
using System;
class Program
{
static void Main()
{
// Step 1: initialize array for example.
char[] array = new char[4];
array[0] = 'p';
array[1] = 'e';
array[2] = 'r';
array[3] = 'l';
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]);
}
Console.WriteLine();
// Step 2: resize the array from 4 to 2 elements.
Array.Resize(ref array, 2);
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]);
}
Console.WriteLine();
}
}
Output
perl
pe
Note: I have used this in implementing hash table buckets. Array.Resize is helpful in optimization tasks.
Caution: If we omit the Array.Resize call, we will get an IndexOutOfRangeException. This exception should be avoided.
IndexOutOfRangeExceptionProgram 2 that uses Array.Resize: C#
using System;
class Program
{
static void Main()
{
// Initialize an array with 5 elements.
char[] arr = new char[5];
arr[0] = 'p';
arr[1] = 'y';
arr[2] = 't';
arr[3] = 'h';
arr[4] = 'o';
// We need an array with 6 elements.
// ... Use Array.Resize to make a new array.
Array.Resize<char>(ref arr, 6);
// Assign the last element.
arr[5] = 'n';
// Display the array.
Console.WriteLine(new string(arr));
}
}
Output
python
So: Array.Resize is a misnomer. It does not resize the array. It replaces the array with a new one of a different size.
And: Most calls will internally invoke Array.Copy. So Array.Copy is the same thing as creating a new array, and copying elements to it.
But: Sometimes Array.Resize can lead to better performance. Arrays boost memory efficiency and lookup speed.
Note: I have used this method to improve performance in a custom hashtable, which could use arrays of buckets and not Lists.
And: This reduced memory usage. In the end, it significantly enhanced performance.