We steal now how to init arrays in vb.NET:
[...]You can also declare an array without specifying the number of elements on one line, you must provide values for each element when initializing the array. The following lines demonstrate that:
| Dim Test() as Integer 'declaring a Test array Test=New Integer(){1,3,5,7,9,} |
Reinitializing Arrays
We can change the size of an array after creating them. The ReDim statement assigns a completely new array object to the specified array variable. You use ReDim statement to change the number of elements in an array. The following lines of code demonstrate that. This code reinitializes the Test array declared above.
| Dim Test(10) as Integer ReDim Test(25) as Integer 'Reinitializing the array |
When using the Redim statement all the data contained in the array is lost. If you want to preserve existing data when reinitializing an array then you should use the Preserve keyword which looks like this:
| Dim Test() as Integer={1,3,5} 'declares an array an initializes it with three members ReDim Preserve Test(25) 'resizes the array and retains the the data in elements 0 to 2 |
Multidimensional Arrays
All arrays which were mentioned above are one dimensional or linear arrays. There are two kinds of multidimensional arrays supported by the .NET framework: Rectangular arrays and Jagged arrays.
Rectangular arrays
Rectangular arrays are arrays in which each member of each dimension is extended in each other dimension by the same length. We declare a rectangular array by specifying additional dimensions at declaration. The following lines of code demonstrate the declaration of a multidimensional array.
| Dim rectArray(4, 2) As Integer 'declares an array of 5 by 3 members which is a 15 member array Dim rectArray(,) As Integer = {{1, 2, 3}, {12, 13, 14}, {11, 10, 9}} 'setting initial values |
Jagged Arrays
Another type of multidimensional array, Jagged Array, is an array of arrays in which the length of each array can differ. Example where this array can be used is to create a table in which the number of columns differ in each row. Say, if row1 has 3 columns, row2 has 3 columns then row3 can have 4 columns, row4 can have 5 columns and so on. The following code demonstrates jagged arrays.
| Dim colors(2)() as String 'declaring an array of 3 arrays colors(0)=New String(){"Red","blue","Green"} initializing the first array to 3 members and setting values colors(1)=New String(){"Yellow","Purple","Green","Violet"} initializing the second array to 4 members and setting values colors(2)=New String(){"Red","Black","White","Grey","Aqua"} initializing the third array to 5 members and setting values |
Keine Kommentare:
Kommentar veröffentlichen