Using the Array.Resize<T> function in C#, you can resize an array. Using this method, you can set a new size for a one-dimensional array's element count. Let's examine its operation and look at a few instances.
The Array.Resize<T> Technique
The definition of the Array.Resize<T> method is as follows:
public static void Resize<T>(ref T[] array, int newSize);
- T: The type of the elements in the array.
- array: The one-dimensional, zero-based array to resize, or null to create a new array with the specified size.
- newSize: The size of the new array.
Let’s look at some examples to understand how resizing affects an array.
Suppose we have the following string array:
We can resize this array to a larger size (five elements larger):
After resizing, the array contains the following values:
Now let’s resize the array to a smaller size (four elements):
After resizing, the array contains the following values:
"The", "quick", "brown", "fox"
- The Array.Resize<T> method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
- If array is null, this method creates a new array with the specified size.
- If newSize is greater than the length of the old array, a new array is allocated, and all the elements are copied from the old array to the new one.
- If newSize is less than the length of the old array, a new array is allocated, and elements are copied from the old array to the new one until the new one is filled; the rest of the elements in the old array are ignored1.
Remember that Array.Resize<T> provides a convenient way to adjust the size of an array dynamically during program execution
0 comments:
Post a Comment