Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Language features - Array

Total Hit ( 8886)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


Arrays allow you to refer to a series of variables by the same name and to use a number, called an index or subscript, to tell them apart. This helps you create shorter and simpler code in many situations, because you can set up loops that deal efficiently with any number of elements by using the index number.

Facts about Array data type

  • An array can have one dimension or more than one. You can specify up to 32 dimensions, although more than three is extremely rare.
  • In VB.net array are contiguous along each dimension from subscript 0 through the highest subscript of that dimension.
  • If you don’t specify array size then you can change it later using ReDim statement.
  • In VB.net every type of array is reference type.
  • An array variable holds a pointer to the data constituting the elements and the rank and length information.
  • All arrays inherit from System.Array class.
  • An array declaration specifies a data type, and all its elements must be of that type.
  • When the data type is Object, the individual elements can contain different kinds of data (objects, strings, numbers, and so on).
  • You can define array of fundamental datatype(i.e. String, Integer, Boolean ...), Structure or of an object class.



Declaring Array Variables

Array can be declared just like all other variables. You can use Dim statement to declare single/multi dimensional array of any type.

Single-Dimensional Array

The following example declares single dimensional array which can store 5 items of string type.

Click here to copy the following block
Dim arrPersons(4) As String

arrPersons(0)="Bob"
arrPersons(1)="Tina"
arrPersons(2)="Jonny"
arrPersons(3)="Kim"
arrPersons(4)="Jim"

Multi-Dimentional Array

Click here to copy the following block
The following example declares 2 dimensional array.

Dim arrPersons(4,2) As String

'//store first name, phone, birthdate
arrPersons(0,0)="Bob"
arrPersons(0,1)="770-334-4445"
arrPersons(0,2)="7/1/1970"

arrPersons(1,0)="Tina"
arrPersons(1,1)="404-233-5644"
arrPersons(1,2)="1/5/1977"

arrPersons(2,0)="Jonny"
arrPersons(2,1)="770-899-1999"
arrPersons(2,2)="8/13/1971"

arrPersons(3,0)="Kim"
arrPersons(3,1)="770-444-2200"
arrPersons(3,2)="12/1/1975"

arrPersons(4,0)="Jim"
arrPersons(4,1)="770-367-4000"
arrPersons(4,2)="11/6/1980"

Jagged Arrays (Array of Arrays)

This is another type of array supported in VB.net. Sometimes the data in your application is two-dimensional but not rectangular. For example you want to store states and its cities in array.

Example

Click here to copy the following block
Sub JaggedArrayDemo()

  '//This variable can store 50 arrays of different size
  Dim arrStateCities(49)() As String

  'First item state code and after that all other items major cities
  arrStateCities(0) = New String() {"AL", "Birmingham", "Montgomery", "Mobile", "Huntsville", "Tuscaloosa", "Hoover", "Dothan", "Decatur", "Auburn"}
  arrStateCities(1) = New String() {"AK", "Anchorage", "Juneau", "Fairbanks", "Sitka", "Ketchikan"}
  arrStateCities(2) = New String() {"AZ", "Phoenix", "Tucson", "Mesa", "Glendale", "Scottsdale", "Chandler", "Tempe", "Gilbert", "Peoria", "Yuma", "Flagstaff"}
  '
  '
  ' More states and their cities
  '
  '
  arrStateCities(49) = New String() {"WY", "Cheyenne", "Casper", "Laramie", "Gillette"}

  Dim statesCnt, citiesCnt As Integer
  For statesCnt = 0 To UBound(arrStateCities)
    '//if state info assigned ?
    If Not arrStateCities(statesCnt) Is Nothing Then
      '//arrStateCities(stateIndex)(0) is state code
      Console.WriteLine("State [" & arrStateCities(statesCnt)(0) & "] : Total Cities => " & UBound(arrStateCities(statesCnt)))
      For citiesCnt = 1 To UBound(arrStateCities(statesCnt))
        Console.Write(arrStateCities(statesCnt)(citiesCnt) & " ")
      Next
      Console.WriteLine(vbCrLf & "================================================")
    End If
  Next
End Sub

Output

State [AL] : Total Cities => 9
Birmingham  Montgomery  Mobile  Huntsville  Tuscaloosa  Hoover  Dothan  Decatur  Auburn  
================================================
State [AK] : Total Cities => 5
Anchorage  Juneau  Fairbanks  Sitka  Ketchikan  
================================================
State [AZ] : Total Cities => 11
Phoenix  Tucson  Mesa  Glendale  Scottsdale  Chandler  Tempe  Gilbert  Peoria  Yuma  Flagstaff  
================================================
State [WY] : Total Cities => 4
Cheyenne  Casper  Laramie  Gillette  
================================================

Initializing Arrays

In VB.net you can initialize an array variable as a part of its declaration. There are certain rules which you must follow when you initialize array variable.

- If you want to initialize an array during variable declaration then you can not define array size after variable name. Parenthesis must be empty.

Example

Click here to copy the following block
Dim A1() As Integer = {} '//Valid : Unitialized array with 0 item
Dim A2(3) As Integer = {} '//Error : Can not initialize array when you define array size.

Dim B1() As Integer = {111,222,333,444} '//Valid : Initialized array with 4 items

- If you use New keyword then it must contain "{}" at the end. Only different thing about using New is you can define size in datatype constructor but still I don’t find it useful coz you can initialize array without using New keyword but lets look at the example for more understanding.

Example

Click here to copy the following block
Dim A1() As Integer = New Integer() {} '//Valid : Unitialized array with 0 item
Dim A2() As Integer = New Integer()   '//Error : Missing {} after Integer()

Dim B1() As Integer = New Integer(3) {} '//Valid : Unitialized array with 4 items
Dim B2() As Integer = New Integer(3)  '//Error : Missing {} after Integer(3)

Dim C1() As Integer = New Integer(3){111,222,333,444} '//Valid : Initialized array with 4 items
Dim C2() As Integer = New Integer(3){111,222} '//Error : Only 2 items assigned in the initialization list (it must be 4 items)

Let's look at few examples which will give you more idea.

Initializing single-dimensional array

The following example declares a single dimensional integer array with 5 items.

Click here to copy the following block
Dim a1() As Integer = {111, 222, 333, 444, 555}
'Or
Dim a2() As Integer = New Integer(4) {111, 222, 333, 444, 555}

The following lines produce error

Click here to copy the following block
'//Error : Explicit bound is not allowed when initializing an array
Dim a1(4) As Integer = {111, 222, 333, 444, 555}
'//Error : Missing "{}"
Dim a2() As Integer = New Integer(4)

If you want to store different types in the same array then you must declare an array of object datatype. Object can hold reference of any type.

Click here to copy the following block
'//Create an array of 4 items
Dim a1() As Object={10, "Test", 12.36, True}

Initializing single-dimensional array

Now let's look at the example which declares a multi dimensional array with initial values.

Click here to copy the following block
'3x2 string array
Dim arrPersons(,) As String = {{"Boby", "770-334-4445", "7/11/1970"}, _
        {"Tina", "404-233-5644", "1/15/1977"}, _
        {"Roni", "334-223-7854", "3/11/1979"}, _
        {"Jhon", "770-899-1999", "8/13/1971"}}

'Or

Dim arrPersons(,) As String =New String(2,2) {{"Boby", "770-334-4445", "7/11/1970"}, _
        {"Tina", "404-233-5644", "1/15/1977"}, _
        {"Roni", "334-223-7854", "3/11/1979"}, _
        {"Jhon", "770-899-1999", "8/13/1971"}}

'Or

Dim arrPersons(,) As String =New String(,) {{"Boby", "770-334-4445", "7/11/1970"}, _
        {"Tina", "404-233-5644", "1/15/1977"}, _
        {"Roni", "334-223-7854", "3/11/1979"}, _
        {"Jhon", "770-899-1999", "8/13/1971"}}

Resizing Arrays

You can resize an array at any time by assigning a different array object to the same array variable, using either ReDim or a standard assignment statement. The new array object can have different dimensions, although it must retain the same rank. This helps you manage memory efficiently. For example, you can use a large array for a short time and then ReDim it to a smaller size. This frees up memory you no longer need.

Note: Instead of using regular arrays with ReDim Preserve consider System.Collections.ArrayList class if you need dynamic array functionality. Dynamic arrays can be a major performance pitfall. Under the covers, when you call ReDim Preserve MyArray(5), VB.NET will actually take the array as it stands before that statement, create a copy of it with the additional positions needed (or a smaller size), then destroy the original copy. This is because there really isn't such a thing as a "dynamic array" in .NET. This is what the System.Collections.ArrayList class was invented for (well, probably for many other reasons too). Check the last section for more info about ArrayList class

When you ReDim an array, its existing values are normally lost. However, you can retain them by including the Preserve keyword in the ReDim statement. For example, the following statement declares a new string array, initializes its elements from the corresponding elements of the existing MyArray, and assigns the new array to MyArray.

Resizing single dimensional array example

Click here to copy the following block
Dim arrPersons(2) As String

arrPersons(0) = "Bob"
arrPersons(1) = "Jim"
arrPersons(2) = "Ron"

ReDim Preserve arrPersons(4) '//Increase array size to 4 and preserve all previous values

arrPersons(3) = "Kim"
arrPersons(4) = "Joe"

ReDim Preserve arrPersons(3) '//Shrink array size by 1, this will remove previous element at index 4

Resizing multi dimensional array example

Click here to copy the following block
Dim arrPersons(4, 0) As String '//1x2 array

'//store first name, phone, birthdate
arrPersons(0, 0) = "Bob"
arrPersons(1, 0) = "Tina"
arrPersons(2, 0) = "Jonny"
arrPersons(3, 0) = "Kim"
arrPersons(4, 0) = "Jim"

'//Error : 'ReDim' can only change the right most dimension
'ReDim Preserve arrPersons(10, 2) '//Increase array size to 4x2 and preserve all previous values

ReDim Preserve arrPersons(4, 2) '//Increase array size to 4x2 and preserve all previous values

arrPersons(0, 1) = "770-334-4445"
arrPersons(0, 2) = "7/1/1970"

arrPersons(1, 1) = "404-233-5644"
arrPersons(1, 2) = "1/5/1977"

arrPersons(2, 1) = "770-899-1999"
arrPersons(2, 2) = "8/13/1971"

arrPersons(3, 1) = "770-444-2200"
arrPersons(3, 2) = "12/1/1975"

arrPersons(4, 1) = "770-367-4000"
arrPersons(4, 2) = "11/6/1980"


Note: ReDim can only change the rightmost dimension for multi dimensional array so if you declare your array of 5x3x4 size then you can not change it to 10x3x4 or 5x5x4, you can only change the right most dimension.

Members of System.Array class

As we discuss earlier that all arrays are inherited from System.Array class which gives some common functionality to all arrays. In this section we will look at few very useful shared methods of System.Array class. The following list the properties and methods supported by all types of arrays.

Public Properties
public propertyIsFixedSize Gets a value indicating whether the Array has a fixed size.
public propertyIsReadOnly Gets a value indicating whether the Array is read-only.
public propertyIsSynchronized Gets a value indicating whether access to the Array is synchronized (thread-safe).
public propertyLength Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.
public propertyLongLength Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.
public propertyRank Gets the rank (number of dimensions) of the Array.
public propertySyncRoot Gets an object that can be used to synchronize access to the Array.

Public Methods
public methodstatic (Shared in Visual Basic)BinarySearch Overloaded. Searches a one-dimensional sorted Array for a value, using a binary search algorithm.
public methodstatic (Shared in Visual Basic)Clear Sets a range of elements in the Array to zero, to false, or to a null reference (Nothing in Visual Basic), depending on the element type.
public methodClone Creates a shallow copy of the Array.
public methodstatic (Shared in Visual Basic)Copy Overloaded. Copies a section of one Array to another Array and performs type casting and boxing as required.
public methodCopyTo Overloaded. Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array.
public methodstatic (Shared in Visual Basic)CreateInstance Overloaded. Initializes a new instance of the Array class.
public methodEquals (inherited from Object) Overloaded. Determines whether two Object
public methodGetEnumerator Returns an IEnumerator for the Array
public methodGetHashCode (inherited from Object) Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
public methodGetLength Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array
public methodGetLongLength Gets a 64-bit integer that represents the number of elements in the specified dimension of the Array
public methodGetLowerBound Gets the lower bound of the specified dimension in the Array
public methodGetType (inherited from Object) Gets the Type
public methodGetUpperBound Gets the upper bound of the specified dimension in the Array
public methodGetValue Overloaded. Gets the value of the specified element in the current Array
public methodstatic (Shared in Visual Basic)IndexOf Overloaded. Returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array
public methodInitialize Initializes every element of the value-type Array
public methodstatic (Shared in Visual Basic)LastIndexOf Overloaded. Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array
public methodstatic (Shared in Visual Basic)Reverse Overloaded. Reverses the order of the elements in a one-dimensional Array or in a portion of the Array
public methodSetValue Overloaded. Sets the specified element in the current Array
public methodstatic (Shared in Visual Basic)Sort Overloaded. Sorts the elements in one-dimensional Array
public methodToString (inherited from Object) Returns a String that represents the current Object.

protected methodFinalize (inherited from Object) Overridden. Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.
protected methodMemberwiseClone (inherited from Object) Creates a shallow copy of the current Object


Sorting array (Array.Sort method)

Array.Sort method sorts an array. This is a very useful method and it has 8 different overloaded versions which can take different arguments to perform different operations. Let's look at few of them.

Click here to copy the following block
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  SortDemo()
End Sub

Sub SortDemo()

  Dim a1() As String = {"DDD", "ccc", "aaa", "BBB", "ddd", "AAA", "bbb", "CCC"}
  Dim myComparer = New myReverserClass

  Console.WriteLine("Original array")
  PrintArray(a1)

  Console.WriteLine("Sort 3 elements starting from index 0")
  Array.Sort(a1, 0, 3)
  PrintArray(a1)

  ' Sorts the entire Array using the default comparer.
  Console.WriteLine("Default sort")
  Array.Sort(a1)
  PrintArray(a1)

  Console.WriteLine("Case in-sensetive sort using custom compararor in reverse order")
  Array.Sort(a1, myComparer)
  PrintArray(a1)

End Sub

Sub PrintArray(ByVal arr As System.Array)
  Dim i As Integer

  For i = 0 To arr.GetUpperBound(0)
    Console.WriteLine(" [{0}] : {1}", i, arr(i))
  Next
  Console.WriteLine("=====================")
  Console.WriteLine()
End Sub

Public Class myReverserClass
  Implements IComparer

  ' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
  Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
    Implements IComparer.Compare
    '//Compare method returns
    '//Returns :
    '//  -1=First argument is less than second argument,
    '//  0=Both equal
    '//  1=First argument is greater than second argument,

    Return New CaseInsensitiveComparer().Compare(y, x)
  End Function 'IComparer.Compare

End Class

Output

Original array
  [0] : DDD
  [1] : ccc
  [2] : aaa
  [3] : BBB
  [4] : ddd
  [5] : AAA
  [6] : bbb
  [7] : CCC
=====================

Sort 3 elements starting from index 0
  [0] : aaa
  [1] : ccc
  [2] : DDD
  [3] : BBB
  [4] : ddd
  [5] : AAA
  [6] : bbb
  [7] : CCC
=====================

Default sort
  [0] : aaa
  [1] : AAA
  [2] : bbb
  [3] : BBB
  [4] : ccc
  [5] : CCC
  [6] : ddd
  [7] : DDD
=====================

Case in-sensitive sort using custom comparer in reverse order
  [0] : ddd
  [1] : DDD
  [2] : ccc
  [3] : CCC
  [4] : bbb
  [5] : BBB
  [6] : aaa
  [7] : AAA
=====================

Locating an Element in an Array (Array.IndexOf method)

Click here to copy the following block
Private Sub FindAnimal()
  Dim ZooAnimals(2) As String
  ZooAnimals(0) = "lion"
  ZooAnimals(1) = "turtle"
  ZooAnimals(2) = "ostrich"
  Dim turtle As Integer
  turtle = (Array.IndexOf(ZooAnimals,"turtle"))
  MsgBox("The turtle is element " & turtle)
End Sub

Fastest Search - Locating an Element in an Array (Array.BinarySearch method)

If your array is sorted and you want to search for some element then the most fasted method will be BinarySearch. This algorithm works only for sorted array so sometimes you will get correct result but in order to work 100% correct array must be sorted.

Click here to copy the following block
Sub ArrDemo()
    Const MAX = 90000000
    Dim arr(MAX) As Long
    Dim pos As Integer
    Dim i As Integer

    For i = 0 To MAX
      arr(i) = i * 2
    Next
    Console.WriteLine("Start BS:" & Date.Now)
    pos = (Array.BinarySearch(arr, 544564))
    Console.WriteLine("End BS:" & Date.Now)

    Console.WriteLine("Start IndexOf:" & Date.Now)
    pos = (Array.IndexOf(arr, 544564))
    Console.WriteLine("End IndexOf:" & Date.Now)

    'BinarySearch took 3 seconds to search across 90000000 items
    'Start BinarySearch :  8/14/2005 3:15:36 PM
    'End BinarySearch  :  8/14/2005 3:15:39 PM

    'IndexOf took 33 seconds to search across 90000000 items
    'Start IndexOf   :  8/14/2005 3:15:39 PM
    'End IndexOf    :  8/14/2005 3:16:12 PM
  End Sub

Reversing the Contents of An Array (Array.Reverse method)

This example declares an array of String objects named Animals, populates it, and then reverses its contents.

Click here to copy the following block
Private Sub ReverseSortAnimals()
  Dim Animals(2) As String
  Animals(0) = "lion"
  Animals(1) = "turtle"
  Animals(2) = "ostrich"
  Array.Reverse(Animals)
End Sub

Copying an array (Array.Copy, Array.CopyTo methods)

There are 2 main methods you can use to copy entire array to destination array.
1. Copy
2. CopyTo

Copy

Copies a section of one Array to another Array and performs type casting and boxing as required.

CopyTo

Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index.

Click here to copy the following block
Dim arr1() As Integer = {10, 20, 30, 40, 50}
Dim arr2() As Integer = {60, 70, 80, 90, 100}

Array.Copy(arr1, 0, arr2, 0, 3) '//copy 3 items from arr1 starting from index 0 to arr2 starting from index 0
'//arr1 : 10, 20, 30, 40, 50
'//arr2 : 10, 20, 30, 90, 100

Dim arr3(10) As Integer
arr1.CopyTo(arr3, 2)

'//arr1 : 10, 20, 30, 40, 50
'//arr3 :  0, 0, 10, 20, 30, 40, 50, 0, 0, 0, 0

Using ArrayList for fast dynamic arrays

The last thing I want to discuss about is new set of classes which can be used to implement dynamic array functionality in VB.net. I know you can use ReDim to grow/shrink an Array but under the cover the ReDim Preserve statement creates a new array - and the elements of the old array get copied into the new one. As this happens under VB.NET implicitly, it won't be noticed except for performance loss. System.Collections.ArrayList is more easier and efficient way to handle dynamic arrays.

Click here to copy the following block
Sub ArrayListDemo()
  Dim arrList As New System.Collections.ArrayList
  Dim arrRD() As Integer
  Dim i As Integer
  Dim dtStart As DateTime

  '//////////////////////////////////////////////
  '//Use ReDim Preserve to create dynamic array
  '//////////////////////////////////////////////
  dtStart = Now
  For i = 0 To 50000
    ReDim Preserve arrRD(i)
    arrRD(i) = i * 5
  Next
  Console.WriteLine("ReDim took " & Now.Subtract(dtStart).TotalMilliseconds & " miliseconds for 50000 elements")

  '//////////////////////////////////////////////
  '//Add elements to ArrayList
  '//////////////////////////////////////////////
  dtStart = Now
  For i = 0 To 50000
    arrList.Add(i * 5)
  Next
  Console.WriteLine("ArrayList took " & Now.Subtract(dtStart).TotalMilliseconds & " miliseconds for 50000 elements")

  '//Change value of first and fifth element
  arrList(0) = 111
  arrList(4) = 555

  '//Read value of first and fifth element
  Console.WriteLine("First element :" & arrList(0))
  Console.WriteLine("Fifth element :" & arrList(4))
End Sub

Output

ReDim took 10046.875 miliseconds for 50000 elements
ArrayList took 15.625 miliseconds for 50000 elements
First element :111
Fifth element :555


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.