Arrays in VB.NET
Arrays are very important programming constructs that allow us to store data during programming and runtime. Various types of data can be stored depending on which datatype is declared. For instance, we will create an example to declare an array to store 5 kinds of fruits Banana, Orange, Apple, Papaya and Strawberry. So we would declare the array as follows :
Dim Fruits(4) as String
Here we have declared the Fruit arrays as string datatype. If we intend to store numeric values, then we will have to declare the array as Integer or Double. Also, the reason we declare the Fruits array as having an index of (4) is because all arrays are zero-based, meaning the array index starts from zero. Hence in this example we will have (0), (1), (2), (3), and (4). We have a total of 5 arrays to store data.
To store the fruit names into the arrays, we will do the following :
Fruits(0) = "Banana"
Fruits(1) = "Orange"
Fruits(2) = "Apple"
Fruits(3) = "Papaya"
Fruits(4) = "Strawberry"
After that, to test the data, we can run the following codes :
MsgBox("The " & Fruits(3) & " is very sweet.")
and the result we get is : The Papaya is very sweet.
For instance somewhere in the application, we decided that we wanted to allow the user to include 2 additional fruits Watermelon and Cherry. We can always allow that by using ReDim.
See the example below:
ReDim Fruits(6)
Guess what, the array has been resized to allow the storing of 7 data. Remember that array is zero-based? Hence, now we have (0),(1),(2),(3),(4),(5),(6). However the initial data that we stored, the Banana, Orange, Apple, Papaya and Strawberry fruits are all gone after we resize the array. In order to preserve the initial data, we need to specified it with the word Preserve as follows:
ReDim Preserve Fruits(6)
Now the initial fruits are preserved and we just add on like this to the arrays
Fruit(5) = "Watermelon"
Fruit(6) = "Cherry"
Back to VB Egg
Subscribe to:
Post Comments (Atom)

0 comments
Post a Comment