How to VB.Net Arrays
Arrays are using for store similar data types grouping as a single unit. It is a fixed collection of same data type that are stored contiguously and that are accessible by an index We specify their length and we can initialize arrays with data. We can access Array elements by its numeric index.
Declaring and Initializing an Integer Array
array(0) = 10
array(1) = 20
array(2) = 30
array(3) = 40
In the above code we declare an Integer Array of four elements and assign the value to array index . That means we assign values to array index 0-4.
We can retrieve these values from array by using a for loop.
We can declare and initialize an array in one statement.
Note that in the above code we did not specify the length of the array so the compiler will do it for us.
How to find the length of an Array ?
We can use array.Length to find the length of an Array.
Declaring and Initializing a String Array
Dim week(6) As String
The above Vb.Net statements means that , an Array named as week declared as a String type and it can have the capability of seven String type values.
week(0) = "Sunday"
week(1) = "Monday"
In the above statement , we initialize the values to the String Array. week(0) = "Sunday" means , we initialize the first value of Array as "Sunday" ,
Dim weekName as String = week(1)
We can access the Arrays elements by providing its numerical index, the above statement we access the second value from the week Array.
In the following program , we declare an Array "week" capability of seven String values and assigns the seven values as days in a week . Next step is to retrieve the elements of the Array using a For loop. For finding the end of an Array we used the Length function of Array Object.
How to resize an array ?
An array can be resized with Array.Resize < T > Method , that means We make an array bigger or smaller. Array.Resize < T > Method Changes the number of elements of a one-dimensional array to the specified new size.
Array.Resize < T > - T is the type of the elements of the array.
This method should be used with only one dimensional Array. This 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.
In the above code we resize the array to 3 elements.
How to Use ForEach with Arrays ?
How to check if a value exists in an array ?
The following program shows how to find a specified value from an Array.
When you execute this program you will get the Days in a Week .