Home

The Array Class

 

Types of Arrays

 

Single-Dimensional Array Creation

An array is a technique of storing information of different items in a common variable of one name. For example, consider the following list:

Store Item
Women Coat
Men Jacket
Teen Jeans
Women Bathing Suit
Children Playground Dress

This type of list can be created using a string-based array. Here is an example:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim lstItemsNames As String() = {"Women Coat", "Men Jacket", "Teen Jeans", _
    				"Women Bathing Suit", "Children Playground Dress"}
End Sub

The above type of list is referred to as a single-dimensional. To provide more information about items, you can associate a second or even a third list to the first as follows:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim itemsNumbers As String() = {"624376", "274952", "497852", "749752", "394085"}
        Dim lstItemsNames As String() = {"Women Coat", "Men Jacket", "Teen Jeans", _
                                        "Women Bathing Suit", "Children Playground Dress"}
        Dim itemsPrices As Double() = {225.55, 175.75, 24.5, 34.65, 75.05}
End Sub

To support arrays, the .NET Framework provides the Array class, which is defined in the System namespace. Based on this, you can formally use the Array class to create an array. To support the creation of an array, the Array class is equipped with the CreateInstance() method that comes in various versions. To create a one-dimensional array, you can use the following version:

Overloads Public Shared Function CreateInstance(ByVal elementType As Type, _
                                                                               ByVal length As Integer) As Array

The first argument is used to specify the type of array you want to create. Since it is declared as Type, you can use the typeof operator to cast your type.

The second argument specifies the number of items of the list. The items in an Array-based list use a zero-based index, meaning that the first item has an index of 0, the second has an index of 1, and so on. Using the Array class, you can create a list of the above item names as follows:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), length)
End Sub

Creating various lists that would be later connected can be confusing and even overwhelming, as mentioned earlier.

 

Practical Learning Practical Learning: Creating a List Class

  1. Start Microsoft Visual Basic .NET or Visual Studio .NET
  2. To start a new application, on the main menu, click File -> New -> Project...
  3. In the Projects Types list, click Visual Basic Projects
  4. In the Templates list, click Windows Application
  5. In the Name box replace the string with DepartmentStore1
  6. To add a project, on the main menu, click File -> Add Project -> New Project...
  7. In the Project Types list, make sure Visual Basic Projects is selected
    In the Templates list, click Class Library (.NET)
  8. Set the Name to StoreItem
  9. Click OK
  10. Change the file as follows:
     
    Public Class CStoreItem
        Private nbr As String
        Private nm As String
        Private sz As String
        Private uprice As Double
    
        Public Sub New()
            nbr = ""
            nm = ""
            sz = ""
            uprice = 0.0
        End Sub
    
    Public Sub CStoreItem(ByVal number As String, ByVal name As String, ByVal size As String, ByVal price As Double)
            nbr = number
            nm = name
            sz = size
            uprice = price
        End Sub
    
        Public Property ItemNumber() As String
            Get
                Return nbr
            End Get
            Set(ByVal Value As String)
                nbr = Value
            End Set
        End Property
    
        Public Property ItemName() As String
            Get
                Return nm
            End Get
            Set(ByVal Value As String)
                nm = Value
            End Set
        End Property
    
        Public Property Size() As String
            Get
                Return sz
            End Get
            Set(ByVal Value As String)
                sz = Value
            End Set
        End Property
    
        Public Property UnitPrice() As Double
            Get
                Return uprice
            End Get
            Set(ByVal Value As Double)
                uprice = Value
            End Set
        End Property
    
    End Class
  11. To create the library, on the main menu, click Build -> Build StoreItem
  12. To get a reference of this library to the department store project, in Solution Explorer, under DepartmentStore1, right-click References and click Add Reference...
  13. In the Add Reference dialog box, click the Projects property page and make sure the StoreItem project is selected:
     
    Add Reference
  14. Click Select and click OK
  15. Display the form of the DepartmentStore1 project
  16. Double-click the body of the form to access its Load event
  17. In the top section of the file, under the Inherits line, type Dim lstItemsInStore As Array
  18. Implement the Load event as follows:
     
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            lstItemsInStore = Array.CreateInstance(GetType(StoreItem.CStoreItem), 6)
    End Sub
  19. Design the form as follows:
     
    Department Store - Form Design
    Control Name Text Other Properties
    Label     Item #:  
    TextBox   txtItemNumber    
    Label     Description:  
    TextBox   txtDescription    
    Label     Size:  
    TextBox   txtSize    
    Label     UnitPrice:  
    TextBox   txtUnitPrice   TextAlign: Right
    Button   btnClose Close  
    Button   btnFirst | <  
    Button   btnPrevious <<  
    Button   btnNext >>  
    Button   btnLast > |  
  20. Save all

The Length of an Array

When creating an array that you are not initializing, you must provide the number of items that the list will contain. This number is passed inside the variable's parentheses as a constant integer. Here is an example:

Private Sub Form1_Load(ByVal sender As System.Object, _
			ByVal e As System.EventArgs) _
			Handles MyBase.Load
        Dim lstItemsNames(5) As String
End Sub

If you create a list using the Array.CreateInstance() method using the above version, you must pass a constant integer as the second argument. Here is an example:

Private Sub Form1_Load(ByVal sender As System.Object, _
			ByVal e As System.EventArgs) _
			Handles MyBase.Load
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), 5)
End Sub

If the array exists already, to find out the number of items it contains, you can access its Length property. Alternatively, you can call the Array.GetLength() method. Its syntax is:

Public Function GetLength(ByVal dimension As Integer) As Integer

For a single dimensional array as those declared above, you must pass the argument as 0. This method returns a 32-bit integer that represents the number of items in the array.

 

Two-Dimensional Array Creation

The type of array we declared earlier is referred to as a single-dimensional. To provide more information about items, you can associate a second or even a third list to the first as follows:

Private Sub Form1_Load(ByVal sender As System.Object, _
			ByVal e As System.EventArgs) Handles MyBase.Load
        Dim lstItemsNames As String() = {"Women Coat", "Men Jacket", "Teen Jeans", _
                                "Women Bathing Suit", "Children Playground Dress"}
End Sub

You can create a two-dimensional array by entering two constant integers separated by a comma in the parentheses of the variable. Here is an example:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim lstItemsNames(2, 3) As String
End Sub

If you want to use the Array.CreateInstance() method to create a two-dimensional array, you can use the following version:

Overloads Public Shared Function CreateInstance( _
   ByVal elementType As Type, _
   ByVal length1 As Integer, _
   ByVal length2 As Integer _
) As Array

The second number of the declaration and the third argument of the current CreateInstance() method specify the number of items that each list would contain. In the above declaration, the number 3 means that each array will be made of three items.

Based on this, here is an example of declaring a two-dimensional array using the CreateInstance() method:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim lstItemsNames(2, 3) As String
        Dim lstItemsNumbers As Array = Array.CreateInstance(GetType(String), 2, 3)
End Sub

To know the total number of items that an array contains, you can access its Length property. To know the number of items that a particular list contains, call the Array.GetLength() method and pass the number corresponding to the array. To know the number of items in the first list, pass the argument as 0. To know the number of items in the second list, pass the argument as 1.

Multidimensional Array Creation

Besides the single or two-dimensional, you can create multidimensional arrays by specifying the number of commas in the square brackets and specifying the numbers. If you want to use the Array.CreateInstance() method to create a multidimensional array, you can call the following version:

Overloads Public Shared Function CreateInstance( _
   ByVal elementType As Type, _
   ByVal ParamArray lengths() As Integer _
) As Array

With this version of the method, the second argument specifies the number of arrays that the variable will hold.

If you want to find out the total number of items that an array contains, access its Length property. To get the number of items that a particular list contains, you can call the Array.GetLength() method and pass the number corresponding to the array.

To know the number of lists that an array variable contains, you can access its Rank property.

 

Operations on Arrays

 

Adding Items to an Array

There are two main techniques you can use to initialize an array. You can create its list of items when declaring the array. Here is an example:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim itemsPrices As Double() = {225.55, 175.75, 24.5, 34.65, 75.05}
End Sub

Another technique is to first declare the array, then initialize each of its members. Here is an example:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim storeItems(4) As String

        storeItems(0) = "Women Coat"
        storeItems(1) = "Women Bathing Suit"
        storeItems(2) = "Quilted Down Jacket"
        storeItems(3) = "Men Jacket"
End Sub

Here is an example for a two-dimensional array:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim storeItems(2, 3) As String

        storeItems(0, 0) = "Women Coat"
        storeItems(0, 1) = "Women Bathing Suit"
        storeItems(0, 2) = "Quilted Down Jacket"
        storeItems(1, 0) = "Men Jacket"
        storeItems(1, 1) = "Children Playground Dress"
        storeItems(1, 2) = "Boys Trousers"
End Sub

The Array class also provides its own support for adding items to an array. This is done using the Array.SetValue() that is overloaded with various versions. To add a new item to a single-dimensional array, you can use the following syntax:

Overloads Public Sub SetValue( _
   ByVal value As Object, _
   ByVal index As Integer _
)

The first argument is the value to add to the list. The second argument is the index of the item to be added. The first item has index 1 the second item has index 2, and so on. Here is an example:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim storeItems(4) As String

        storeItems.SetValue("Women Coat", 0)
        storeItems.SetValue("Women Bathing Suit", 1)
        storeItems.SetValue("Quilted Down Jacket", 2)
        storeItems.SetValue("Men Jacket", 3)
End Sub

The Array class provides a SetValue() version for each corresponding CreateInstance() method we reviewed earlier.

Practical Learning Practical Learning: Adding Items to an Array

  1. To populate the array, change the Load event as follows:
     
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            lstItemsInStore = Array.CreateInstance(GetType(StoreItem.CStoreItem), 6)
    
            Dim anItem As StoreItem.CStoreItem
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "724372"
            anItem.ItemName = "Women Coat"
            anItem.Size = "Large"
            anItem.UnitPrice = 225.55
            lstItemsInStore.SetValue(anItem, 0)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "624376"
            anItem.ItemName = "Men Jacket"
            anItem.Size = "Medium"
            anItem.UnitPrice = 175.75
            lstItemsInStore.SetValue(anItem, 1)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "274952"
            anItem.ItemName = "Teen Jeans"
            anItem.Size = "14"
            anItem.UnitPrice = 24.5
            lstItemsInStore.SetValue(anItem, 2)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "497852"
            anItem.ItemName = "Women Bathing Suit"
            anItem.Size = "Petite"
            anItem.UnitPrice = 34.65
            lstItemsInStore.SetValue(anItem, 3)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "749752"
            anItem.ItemName = "Children Playground Dress"
            anItem.Size = "12"
            anItem.UnitPrice = 75.05
            lstItemsInStore.SetValue(anItem, 4)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "394085"
            anItem.ItemName = "Boys Trousers"
            anItem.Size = "8"
            anItem.UnitPrice = 17.95
            lstItemsInStore.SetValue(anItem, 5)
    End Sub
  2. Save all

Accessing the Members of an Array

Probably the most regularly performed operation on a list consists of retrieving the values of its members. You access the member of an array using its index as we saw earlier. To perform the same operation, the Array class is equipped with the GetValue() method that is overloaded with a version corresponding to each version of the CreateInstance() and the SetValue() methods. For example, to access the values stored in a one-dimensional array, you can call call this version:

Overloads Public Function GetValue(ByVal index As Integer) As Object

The argument is the zero-based index of the member whose value you want to access. If you pass an invalid value, the computer would throw an IndexOutOfRangeException exception.

Practical Learning Practical Learning: Accessing the Members of an Array

  1. In the top section of the file, under the Inherits line, declare the following variable:
     
    Public Class Form1
        Inherits System.Windows.Forms.Form
        Dim lstItemsInStore As Array
        Dim CurrentPosition As Integer
  2. In the Class Name combo box, select btnClose
  3. In the Method Name combo box, select Click and implement its Click event as follows:
     
    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
            Close()
    End Sub
  4. In the Class Name combo box, select btnFirst
  5. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFirst.Click
            CurrentPosition = 0
    
            Try
                Dim anItem As StoreItem.CStoreItem = lstItemsInStore.GetValue(CurrentPosition)
    
                Me.txtItemNumber.Text = anItem.ItemNumber
                Me.txtDescription.Text = anItem.ItemName
                Me.txtSize.Text = anItem.Size
                Me.txtUnitPrice.Text = anItem.UnitPrice.ToString("C")
            Catch ex As IndexOutOfRangeException
                MsgBox("Invalid Index: Contact the administrator and report this error")
            End Try
    End Sub
  6. In the Class Name combo box, select btnPrevious
  7. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnPrevious_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrevious.Click
            If CurrentPosition = 0 Then
                Exit Sub
            Else
                CurrentPosition = CurrentPosition - 1
    
                Try
    	dim anItem as StoreItem.CStoreItem  = lstItemsInStore.GetValue(CurrentPosition)
    
                    Me.txtItemNumber.Text = anItem.ItemNumber
                    Me.txtDescription.Text = anItem.ItemName
                    Me.txtSize.Text = anItem.Size
                    Me.txtUnitPrice.Text = anItem.UnitPrice.ToString("C")
                Catch ex As IndexOutOfRangeException
                    MsgBox("Invalid Index: Contact the administrator and report this error")
                End Try
            End If
    End Sub
  8. In the Class Name combo box, select btnNext
  9. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click
            If CurrentPosition = (lstItemsInStore.GetLength(0) - 1) Then
                Exit Sub
            Else
                CurrentPosition = CurrentPosition + 1
    
                Try
                    Dim anItem As StoreItem.CStoreItem = lstItemsInStore.GetValue(CurrentPosition)
    
                    Me.txtItemNumber.Text = anItem.ItemNumber
                    Me.txtDescription.Text = anItem.ItemName
                    Me.txtSize.Text = anItem.Size
                    Me.txtUnitPrice.Text = anItem.UnitPrice.ToString("C")
                Catch ex As IndexOutOfRangeException
                    MsgBox("Invalid Index: Contact th administrator and report this error")
                End Try
            End If
    End Sub
  10. In the Class Name combo box, select btnLast
  11. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub btnLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLast.Click
            CurrentPosition = lstItemsInStore.GetLength(0) - 1
    
            Try
                Dim anItem As StoreItem.CStoreItem = lstItemsInStore.GetValue(CurrentPosition)
    
                Me.txtItemNumber.Text = anItem.ItemNumber
                Me.txtDescription.Text = anItem.ItemName
                Me.txtSize.Text = anItem.Size
                Me.txtUnitPrice.Text = anItem.UnitPrice.ToString("C")
            Catch ex As IndexOutOfRangeException
                MsgBox("Invalid Index: Contact the administrator and report this error")
            End Try
    End Sub
  12. In the Class Name combo box, select (Form1 Events)
  13. In the Method Name combo box, select Load and change it as follows:
     
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            lstItemsInStore = Array.CreateInstance(GetType(StoreItem.CStoreItem), 6)
            CurrentPosition = 0
            Dim anItem As StoreItem.CStoreItem
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "724372"
            anItem.ItemName = "Women Coat"
            anItem.Size = "Large"
            anItem.UnitPrice = 225.55
            lstItemsInStore.SetValue(anItem, 0)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "624376"
            anItem.ItemName = "Men Jacket"
            anItem.Size = "Medium"
            anItem.UnitPrice = 175.75
            lstItemsInStore.SetValue(anItem, 1)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "274952"
            anItem.ItemName = "Teen Jeans"
            anItem.Size = "14"
            anItem.UnitPrice = 24.5
            lstItemsInStore.SetValue(anItem, 2)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "497852"
            anItem.ItemName = "Women Bathing Suit"
            anItem.Size = "Petite"
            anItem.UnitPrice = 34.65
            lstItemsInStore.SetValue(anItem, 3)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "749752"
            anItem.ItemName = "Children Playground Dress"
            anItem.Size = "12"
            anItem.UnitPrice = 75.05
            lstItemsInStore.SetValue(anItem, 4)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "394085"
            anItem.ItemName = "Boys Trousers"
            anItem.Size = "8"
            anItem.UnitPrice = 17.95
            lstItemsInStore.SetValue(anItem, 5)
    
            btnFirst_Click(sender, e)
    End Sub
  14. Execute the application to test it
     
  15. Close the form
 

The Arrangement of the List

When a new item is added to the array, it assumes the last position. If you want, you can re-arrange the list in a consecutive order. If the list is a one-dimensional array made of strings, you can arrange it in alphabetical order. If it is made of numbers, you can order them in increment or decrement order. If the list is a two, three, or multi-dimensional array, you can arrange it based on a list-part of your choice. To support the ability to re-organize the list, the Array class is equipped with the Sort() method that is overloaded with as many versions as you can possibly need.

To arrange a single-dimensional array in a consecutive order, you can call the following version of the Array.Sort() method:

Overloads Public Shared Sub Sort(ByVal array As Array)

To reverse the sequence of items of a one-dimensional array, you can call the Array.Reverse() method. Its syntax is:

Overloads Public Shared Sub Reverse(ByVal array As Array)

 

Looking for an Item in an Array

When using a list, you may want to know whether a particular item exists in the list. There are usually two ways to perform this operation. You usually can use a loop to scan a list. With this approach, you navigate through the list by visiting the index of each item and checking the value of that index. Another solution consists of writing a function to perform the search. The Array class provides its own support of both solutions using various methods that can be used to perform this operation.

The Array.IndexOf() method scans a list by accessing the index of each item. This method is overloaded with three versions. To apply it on a single-dimensional array, use the following version:

Overloads Public Shared Function IndexOf( _
   ByVal array As Array, _
   ByVal value As Object _
) As Integer

This method visits each member of the array, looking for the value. Once it finds value in the array, it stops and returns the index where the first occurrence of value was found. The IndexOf() method actually looks for the first occurrence of an item in an array. If you prefer to get the last occurrence of that item in the array, you can call the Array.LastIndexOf() method. It also is overloaded in three versions.

 

Home Copyright © 2004-2010 FunctionX, Inc.