Sometimes we will need to store data in the form of an array. We’ve already seen such arrays in the tutorial on loops but as for a reminder. arrays have a fixed size in memory (technically). They start at index 0 and can contain a defined type of element. In other words, it’s like a variable containing multiple elements of a same kind.
When you declare an array, you should set its size to make sure you have defined bounds to stick with. Here is what is might look like.
Dim Strings(2) As String Strings = {"Alexandre", "Daniel", "Maxime"}
Strings(2) defines the size of the array. It can go from 0 to 2, in other words, it has 3 compartment inside. In the following line we store 3 elements in the array upfront (we don’t have to do this, we can simply declare an empty array).
You can populate or display this array with loops as well! Here is an example with an array of Integer values.
Module Program Dim _Rnd As Random Sub Main() _Rnd = New Random() 'Another way to define a single dimension array Dim ArrayOfInt = New Integer(10) {} 'Go through the array and set a random value to each position For Index As Integer = 0 To 10 Step 1 ArrayOfInt.SetValue(_Rnd.Next(0, 1000), Index) Next 'Go through the array and display every value For Index As Integer = 0 To ArrayOfInt.Length - 1 Step 1 Console.WriteLine(ArrayOfInt.GetValue(Index)) Next 'Stop the Console to wait for user input Console.ReadKey() End Sub End Module
This is the whole code of the Main file. The first thing you may notice is our Random class declaration at the top, we’re going to use it to populate our array with random values.
Next, I am showing you another way of defining an array (with the keyword New). In this case, it contains 11 memory spaces, from 0 to 10 included. This can be a bit tricky honestly, but if you run a debug session with breakpoints, you can hover on the array to see all the spaces as shown below.
In the first loop, I use the method SetValue(ValueToSet, Index) on the ArrayOfInt variable to set to one index after the other a random value from _Rnd.Next(…). Notice that I am using the _Rnd.Next method on the fly inside the argument, meaning that the returned value of this method (the random number generated) will be passed to SetValue as the first argument.
In the second loop, I am doing processing that could have been done in the first loop all at once but I really want to point out how you can pull everything back from another method or somewhere else in you program. In this case, I am using the GetValue(…) method which takes an Index in the table as an argument and returns the associated value.
Notice the ArrayOfInt.Length which returns the current length of the array (11 in this case), we have to remove 1 to this value to fetch this array from 0 to 10, else we will get an IndexOutOfBound exception meaning that we’ve tried to access a value outside of the bounds of the array. Careful with that, put some breakpoints if you’re not entirely sure of what is going on! Remember this is all about you controlling the computer, not the other way around.
Another thing, ArrayOfInt.Length does not take () at the end, why? Because it is not a method, it’s a parameter. In other words, it’s like a variable being shared by the array for us to use. That’s why we can access it like a standard variable by naming the local array, dot, the parameter name.
Same code, but quicker to write
I want to show you a variant to the code above.
Module Program Dim _Rnd As Random Sub Main() _Rnd = New Random() 'Another way to define a single dimension array Dim ArrayOfInt = New Integer(10) {} 'Go through the array and set a random value to each position For Index As Integer = 0 To 10 Step 1 ArrayOfInt(Index) = _Rnd.Next(0, 1000) Next 'Go through the array and display every value For Index As Integer = 0 To ArrayOfInt.Length - 1 Step 1 Console.WriteLine(ArrayOfInt(Index)) Next 'Stop the Console to wait for user input Console.ReadKey() End Sub End Module
Have you noticed the differences? ArrayOfInt(Index) and ArrayOfInt(Index) = _Rnd.Next(0, 1000). We bypass the GetValue and SetValue to use the parenthesis only. It is closer to the C# way of doing things with the square brackets “[]”. I personally find this practice more intuitive and easy. But you have the choice, they are equivalent. Again, I strongly suggest you pick one method or the other and stick with it as a standard.
Technically speaking, we call this kind of practice using an indexer. Your variable, for example ArrayOfInt(IndexOfTheElementTOReturn), and you can set it the same way ArrayOfInt(IndexOfElementToSet) = ElementToSet. You really should try it out because it might not seem quite logical when you first see it in action.
Here is the result it should give you after the execution (Start).
Multiple dimensions!
A single dimension array is like a table containing objects of your defined type but you can also have an array of arrays containing objects of your defined type! Don’t worry it’s not that complicated to visualize, the tricky part is to fill it and fetch it to retrieve the information back. Here is a graphical representation to help you a bit.
Just to give you an idea of what a 2 dimensional array looks like. The first column to the left is the Index of each array, in fact, what’s on the right (the arrays) are contained inside the left most column. If you had a 3 dimensional array it would be similar but all the arrays inside would contain another array. That makes a lot of arrays!
How do you create a 2 dimensional array? It is fairly similar to creating a single dimensional but with a little variant, see the code below.
Dim MultiDimensionalArrayOfInt = New Integer(10, 10) {}
Similar isn’t it? The only difference is that you have to add a new number after the 10 to tell Visual Basic that this is an array of 11 positions of arrays of 11 positions. If you would like to put any initial values, you can add them in the curly brackets like { {0, 32, 323, 7, 43, 32, 12, 23, 392, 3, 12}, …}. In the way it as been declared and initialized, the array we’re using is empty, that’s why we have to fill it up!
Now the tricky part! How to populate and get information from this 2 dimensional array.
Module Program Dim _Rnd As Random Sub Main() _Rnd = New Random() Console.WriteLine("---MultiDimensional Array example---") Dim MultiDimensionalArrayOfInt = New Integer(10, 10) {} 'Nested loops to populate the 2 dimensional array For Index As Integer = 0 To 10 Step 1 For InnerIndex As Integer = 0 To 10 Step 1 MultiDimensionalArrayOfInt(Index, InnerIndex) = _Rnd.Next(0, 1000) Next Next 'Nested loops to read the values inside the 2 dimensional array For Index As Integer = 0 To 10 Step 1 Console.WriteLine("Row number {0}", Index) For InnerIndex As Integer = 0 To 10 Step 1 Console.WriteLine(MultiDimensionalArrayOfInt(Index, InnerIndex)) Next Next 'Stop the Console to wait for user input Console.ReadKey() End Sub End Module
Nested loops are difficult to understand at first, don’t blame yourself if you are not quite sure what is going on here. The solution to the problem is most of the time, put a (or many) breakpoints and see what is really going on when you go through the code step by step. The first loops go through the left most column in the example and the second loop go through each element of the rows. In our example, both arrays are the same size, but if you were to have an array of a larger or smaller size you would have to adjust the “To 10” statement of the corresponding array.
In the previous screenshot, you can see part of the list of elements, the first number is the column and the second is the row in our diagram above.
This is not a simple subject and if you need more in-depth details, feel free to visit the MSDN Website on the subject or to post comments below!
In the next tutorial we will push this topic a bit more with the Generic collections. Generic collections are arrays that can expand in memory. They are a lot more useful and easy to manage in my opinion. They can also be faster at doing some specific tasks. We call this type of collections, data structures.
No Comments Yet!
You can be first to comment this post!