Arrays


  • Arrays are a way to manage groups of similar typed values or objects. With arrays, you can group a series of variables and refer to them with an index.
  • You can also create arrays with multiple dimensions.
  • Arrays in the .NET Framework have built in functionality to facilitate many tasks.
  • Array variables can have the Public, Protected, Friend, Private or Protected Friend specifier.
  • Declaring and Initializing Arrays:
  • Dim a(15) As Integer

    In the above statement a is the name of the array and 15 is the upper bound of the array. This upper bound is the number that specifies the index of the last element. The index of the first element is zero. Thus the array a can contain 16 elements.
    Initial values can be provided for an array by enclosing them in braces and separating them with commas.
    Dim a() As Integer
    a =New Integer() {0,1,2,3,4,5}

Different ways of declaring and initializing Arrays
Module Module1
Sub Main()
Dim a() As Integer
Dim i As Integer
a = New Integer() {0, 1, 2, 3, 4, 5}
System.Console.WriteLine("Array a")
For i = 0 To 5
System.Console.WriteLine(a(i))
Next i
Dim b() As Integer = {5, 10, 15}
System.Console.WriteLine("Array b")
For i = 0 To 2
System.Console.WriteLine(b(i))
Next i
Dim c(3) As Integer
c = New Integer() {1, 2, 3}
System.Console.WriteLine("Array c")
For i = 0 To 2
System.Console.WriteLine(c(i))
Next i
Dim d(5) As Integer
System.Console.WriteLine("Array d")
For i = 0 To 5
System.Console.WriteLine(d(i))
Next i
End Sub
End Module

ReDim statement

To change the number of elements in an array the statement ReDim must be used.
Example:

Dim a() As Integer
a = New Integer() {0, 1, 2, 3, 4, 5}
Dim i As Integer
ReDim a(7)

But in this case the old contents of array a is lost because the array is reinitialized. But you can preserve existing data when reinitializing an array using the Preserve keyword.

Dim b() As Integer = {5, 10, 15}
ReDim Preserve b(8)
Implementing Typecasting
  • An explicit conversion from one type to another type is possible.
  • Typecasting in VB.NET is implemented by means of the CType() statement
Example:
Dim longNum As Long
Dim doubleNum As Double
Public Sub t()
System.Console.WriteLine("Type Casting")
longNum = 500
System.Console.WriteLine("Long " & longNum)
doubleNum = CType(longNum, Double)
System.Console.WriteLine("doubleNum " & doubleNum)
End Sub


Decision statements << Previous

Next >> Procedures and Function

Our aim is to provide information to the knowledge seekers. 



comments powered by Disqus
Footer1