Using Arrays and Collections

Dim prices(4) declares indexes 0 to 4, FIVE elements, because VB.NET arrays are declared by upper bound; ReDim Preserve grows them, and ArrayList grows itself.

10 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

How many items fit on a bill?

ShopKeeper's first bill design uses an array: space for the items of one purchase.

Dim items(9) As String

Customer number 3 buys 11 things.

You have met this wall twice before: BCA104's C arrays, and BCA403's Unit 5 hook, where it pushed us to build linked lists. VB.NET offers 2 gentler answers today: an array that can be re-dimensioned, and a collection that grows by itself. But first, a VB array surprise that catches every Java-trained eye.

Theory

Declared by upper bound, not by count

Read this line with fresh eyes:

Dim prices(4) As Double

In C or Java, the 4 would mean 4 elements. In VB.NET it is the highest index: the array runs from prices(0) to prices(4), which is 5 elements, and prices.Length says 5.

Access uses parentheses, not brackets: prices(0) = 40. Both facts are pure syntax, and both are worth a mark apiece in almost every BCA404 paper.

Practical

Arrays, ReDim, and the self-growing ArrayList

Imports System.Collections

Module BillDemo
    Sub Main()
        Dim prices(2) As Double        ' indexes 0..2: THREE slots
        prices(0) = 40 : prices(1) = 100 : prices(2) = 60
        MsgBox(prices.Length)          ' 3

        ReDim Preserve prices(4)       ' grow to 5 slots, KEEP the 3 values
        prices(3) = 25

        Dim items As New ArrayList()   ' grows by itself
        items.Add("Soap")
        items.Add("Tea")
        items.Add("Rice")
        items.Remove("Tea")
        MsgBox(items.Count)            ' 2

        For Each thing As Object In items
            MsgBox(CStr(thing))        ' Soap, then Rice
        Next
    End Sub
End Module

Quiz

Dim qty(4) As Integer. How many elements does this array hold?

  1. 4, indexes 1 to 4
  2. 4, indexes 0 to 3
  3. 5, indexes 0 to 4
  4. It depends on Option Strict
Show the answer

5, indexes 0 to 4

VB.NET declares arrays by UPPER BOUND: qty runs 0 through 4, five elements, Length 5. Option B is the Java/C reading of the same line, the exact habit this question is hunting: in those languages new int[4] meant 4 elements. Option A invents 1-based arrays, which VB.NET does not have (its arrays start at 0, only its classic STRING functions count from 1: last lesson). Option D drags an unrelated compiler setting in; Option Strict governs conversions, never array sizing.

Think first

ReDim vs ReDim Preserve

The bill array holds 40, 100, 60. One student writes ReDim prices(4), another ReDim Preserve prices(4). Before tapping: what does each array contain afterwards?

Show the answer

Plain ReDim prices(4) allocates a fresh 5-slot array: all zeros; the 40, 100, 60 are GONE. ReDim Preserve prices(4) allocates 5 slots and copies the old values across: 40, 100, 60, 0, 0. One keyword, an entire bill saved or wiped. Preserve costs a full copy, so growing one slot at a time in a loop is wasteful, and that hint (repeated unpredictable growth) is exactly the signal to stop resizing arrays and use a collection instead.

Theory

ArrayList: the bag that grows

Dim items As New ArrayList() (from System.Collections) needs no size, ever:

  • items.Add("Soap") appends; items.Remove("Tea") deletes by value; items.RemoveAt(0) by position
  • items.Count is the live size; items(0) reads by index

One honest cost: ArrayList stores everything As Object. Strings slide in as references, but adding an Integer boxes it (the boxing lesson, cashing its cheque), and reading it back needs CInt. The typed modern cousin, List(Of Double), skips the boxing and refuses wrong types at compile time.

Watch out

Three array slips to avoid

Brackets: prices[0] is not VB; parentheses only. (Confusingly, the same parentheses also call functions: context decides.)

Off the end: prices(5) on a (4)-declared array throws IndexOutOfRangeException at run time; the compiler does not save you.

Plain ReDim in a keep-the-data situation: silent, compiles, wipes the array. If the values matter, the word Preserve matters.

Theory

Which container, when

Decide like a shopkeeper: fixed rack sizes you know in advance (7 weekday totals) suit an array; a bill whose length depends on the customer suits an ArrayList (or List(Of T)). ShopKeeper's bill is the second kind, and from Unit 3 onward its items will live in a collection feeding a DataGrid. And remember BCA403's Unit 5: linked lists solved this same problem BY HAND; collections are that idea, pre-built and shelf-bought.

Summary

Key takeaways

  • Dim a(4) As Integer declares the UPPER BOUND: indexes 0..4, 5 elements, Length 5.
  • VB arrays use parentheses for elements: a(0); out-of-range access fails at run time.
  • ReDim resizes but wipes; ReDim Preserve resizes and keeps the data (at the cost of a copy).
  • ArrayList grows and shrinks itself: Add, Remove, RemoveAt, Count.
  • ArrayList stores Objects: value types get boxed; List(Of T) is the typed, box-free alternative.
  • For Each walks arrays and collections alike.
  • Memory hook: the number in brackets is the top index, not the head-count.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Programming in Visual Basic .NET

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Using Arrays and Collections · .NET Programming · Gri-Learn