Preface
Arrays store multiple very commonly used data structures of the same type. Its length is fixed, that is, the size of the array is fixed once it is created. C# arrays do not support dynamic lengths. So is there a way to adjust the array size in C#? This article will introduce a method to adjust the size of a one-dimensional array through examples.
method
An array instance is an object that inherits the type from a class. We can use the <T> method to adjust the array size. This method only allows us to change the number of elements in a one-dimensional array to the specified size.
1. Method definition:
The Resize method is defined as follows:
public static void Resize<T>(ref T[] array, int newSize);
T:The type of elements in the array.
Array:A one-dimensional array that needs to be resized, an array based on zeros, or empty to create a new array with a specified size.
newSize:Adjusted array size.
Example
We use some examples to understand how resizing affects an array.
1. To increase the array:
using System; namespace { internal class Program { static void Main(string[] args) { // Define array string[] carriers = { "ZTO", "SF", "YTO", "JT", "EMS", "YUNDA"}; // Output Array size: 6 ("Array size:{0}",); // Resize the array to a larger size (ref carriers, +5); // Output Adjusted array size: 11 ("调整后Array size:{0}", ); // Exit any key (); } } }
2. Dunk the array:
using System; namespace { internal class Program { static void Main(string[] args) { // Define array string[] carriers = { "ZTO", "SF", "YTO", "JT", "EMS", "YUNDA"}; // Output Array size: 6 ("Array size:{0}",); // Resize the array to a larger size (ref carriers, 4); // Output Adjusted array size: 4 ("调整后Array size:{0}", ); // Output ZTO SF YTO JT for (int i = 0; i < ; i++) { // Output the corrected array element ("{0} ", carriers[i]); } // Exit any key (); } } }
matter
1、The method allocates a new array of the specified size and copies the elements from the original array to the new array, and then replaces the original array with the new array.
2、If the array is empty, a new array of specified size is created.
3、If newSize is greater than the length of the original array, a new array is allocated and all elements of the original array are copied to the new array.
4、If newSize is less than the length of the original array, a new array is allocated and the original array elements are filled to the new array until the new array is filled, and the remaining elements in the original array are ignored.
summary
This is the end of this article about how to adjust the size of arrays in C#. For more related content on C# array size adjustment, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!