Creating Array in Visual Basic .NET

August 23, 2017

In this lesson I am going to create simple array to hold the days of the week
I need string array and I need seven elements to hold days
So I can define the array

Dim week(6) As String

I have put 6 instead of 7.
why?
Numbering start at zero, although you put 6 there it has 7 elments

Now we will assign days for each elements

week(0) = "Sunday"
week(1) = "Monday"
week(2) = "Tuesday"
week(3) = "Wednesday"
week(4) = "Thursday"
week(5) = "Friday"
week(6) = "Saturday"

Now I need to iterate through all elements through the array. I can use either For…Next loop or For…Each Next loop
I will use For…Each Next loop first

  For Each day As String In week
     Console.WriteLine("Day is " + day)
  Next

Output

Day is Sunday
Day is Monday
Day is Tuesday
Day is Wednesday
Day is Thursday
Day is Friday
Day is Saturday

 


This is the other method of iterating the array. It is For…Next method

    For i = 0 To 6
         Console.WriteLine("Day is " + week(i))
    Next

Initializing arrays with Values
You can initialize the array when you define it . It can be done in single line of code

  Dim week() As String = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}

You do not have to define the upper bound of the array. You can leave it with empty parentheses