Array Methods
There are many operations you can perform on an array.
We'll use this array for the examples below:
string[] fruits = { "mango", "apple", "kiwi", "banana" };
Sort
Array.Sort puts the elements in ascending order. Numbers go smallest to biggest, strings go alphabetically.
Array.Sort(fruits); // apple, banana, kiwi, mango
It sorts in place, so it doesn't return anything (only the OG array is changed):
string[] sorted = Array.Sort(fruits); // ❌ Error: Sort returns void
Reverse
Array.Reverse flips the order of the elements (Also in place):
Array.Reverse(fruits); // mango, kiwi, banana, apple
Want descending order? Sort first, then reverse :^)
Array.Sort(fruits);
Array.Reverse(fruits); // mango, kiwi, banana, apple
Resize
⚠️ Read the Passing Arrays to Functions Notes prior to playing with
Resize
The Array Method Array.Resize gives the impression of changing the array size. However, this method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the reference of the old array with the new one.
Since it swaps out the reference, you have to pass the array with ref:
Array.Resize(ref fruits, 6); // grow to 6 items
Growing adds default values at the end:
| index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| value | "mango" | "apple" | "kiwi" | "banana" | null | null |
Shrinking chops items off the end. They're gone for good!
Array.Resize(ref fruits, 2); // only index 0 and 1 survive