C# declare array(with values) and resize to add elements

Lionsure 2020-08-11 Original by the website

After the array is defined, the new elements cannot be expanded arbitrarily like arraylist. You have to use the array resize method to redefine the length of array, then define the new element type, and then add elements; after defining the new array, the original array is discarded; In terms of memory allocation, a new section of memory will be allocated to the new array instead of expanding on the basis of the original allocated memory, that is, more memory resources will be consumed.

After understanding the array resize method, let's look at an example of using it to extend new elements, starting with C# declare array and add elements.

 

1. C# declare array and initializes it with an object

string[] array = new string[3];
       array[0] = "123";
       array[1] = "abc";
       array[2] = "cde";

 

2. Declare array C# with values(i.e. C# create array with initial values)

int[] arrNum = new int[3]{ 1, 2, 3 };
       string[] arrStr = new string[3]{ "a", "b", "c" };

Or

int[] arrNum1 = { 1, 2, 3 };
       string[] arrStr1 = {"a", "b", "c"};

 

3. C# array resize to add elements

Array.Resize<string>(ref array, (array.Length + 3));
       array[3] = "fgh";
       array[4] = "jkl";
       array[5] = "mn";

for (int n = 0; n < array.Length; n++)
              Response.Write("<br />" + array[n]);

Output result:

abc
       cde
       fgh
       jkl
       mn

The Resize method has two arguments, one is the original array, and the other is the length of new array, that is, the length of original array plus the number of elements to be added, such as array.Length + 3 in the example.

As for the release of the memory resources occupied by the original array, you can ignore it, and the GC will automatically reclaim it; if you require immediate release, you can force the GC to reclaim it, but it is best not to do so, the program may cause an exception.

 

The above is a simple example, in actual use, it can be used to define the field type of the database table. For example, the fields of inserting and updating records are usually different. In this case, you can use the array resize method to expand the array elements.