Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Collections and LINQ

Arrays and Lists

Learn VB.NET arrays and List(Of T) - declaring, upper bounds, ReDim Preserve, multidimensional and jagged arrays, adding, removing, sorting and searching, with C# stand-ins you can run.

Almost every program keeps groups of values: scores, names, orders, pixels. Visual Basic .NET gives you two everyday tools for that: the fixed-size array and the growable List(Of T). Both live in the .NET class library, so everything in this lesson works the same way in C# and F#.

The VB.NET compiler is not available on this site. VB code in this lesson is shown read-only, and the runnable blocks are C# stand-ins that call exactly the same .NET types (int[], List<T>, Array.Sort). Because the library is identical, the behavior you see is the behavior your VB program will have.

Arrays: a fixed number of slots

In VB the number in an array declaration is the upper bound, not the length. This is the single most surprising rule for people coming from C-like languages.

VB
Dim scores(4) As Integer        ' indexes 0..4, so FIVE elements
Dim names() As String = {"Ada", "Linus", "Grace"}
Dim primes As Integer() = New Integer() {2, 3, 5, 7}

scores(0) = 90
Console.WriteLine(scores.Length)           ' 5
Console.WriteLine(names.GetUpperBound(0))  ' 2

Index 0 is the first element. Length is the count, GetUpperBound(0) is the last valid index. Reading outside the range throws IndexOutOfRangeException. The C# stand-in below shows the same facts; note that C# writes the length (new int[5]) where VB writes the upper bound (scores(4)).

C# Array length versus upper bound

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Resizing: ReDim, Preserve and why to avoid them

An array never changes size. VB's ReDim creates a new array and, with Preserve, copies the old values into it:

VB
Dim data(2) As Integer
data(0) = 1 : data(1) = 2 : data(2) = 3
ReDim Preserve data(4)      ' now 5 slots; 1,2,3,0,0

Without Preserve, ReDim throws the old contents away. Under the hood ReDim Preserve is Array.Resize, which allocates and copies every time. Calling it in a loop is slow, which is the main reason to switch to List(Of T) when the size is not known in advance.

C# What ReDim Preserve really does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last line prints False: a brand-new array was created. Any other variable still pointing at the old array does not see the change.

List(Of T): the growable collection

List(Of T) wraps an array and grows it for you, doubling the internal capacity when it is full, so adding is cheap on average.

VB
Dim todo As New List(Of String)
todo.Add("Write lesson")
todo.Add("Run tests")
todo.AddRange({"Deploy", "Celebrate"})
todo.Insert(0, "Plan")
todo.Remove("Run tests")
Console.WriteLine(todo.Count)
For Each item In todo
    Console.WriteLine(item)
Next

Useful members: Count, Add, AddRange, Insert, Remove, RemoveAt, RemoveAll(predicate), Contains, IndexOf, Clear, Sort, Reverse, ToArray. A collection initializer such as New List(Of Integer) From {3, 1, 2} fills it at creation.

C# List operations (C# stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Sorting and searching

Array.Sort(arr) and list.Sort() sort in place using the type's default order. For custom order pass a comparison:

VB
people.Sort(Function(a, b) a.Age.CompareTo(b.Age))
Dim pos = Array.BinarySearch(sortedArray, 42)   ' array MUST be sorted

BinarySearch returns the index if found, or a negative number (the bitwise complement of the insertion point) if not. Array.IndexOf and list.Find(predicate) work on unsorted data with a linear scan.

Multidimensional and jagged arrays

A rectangular array has one fixed shape; a jagged array is an array of arrays whose rows may differ in length.

VB
Dim grid(2, 3) As Integer          ' 3 rows x 4 columns
grid(1, 2) = 7
Dim jagged(2)() As Integer         ' three rows, each set later
jagged(0) = New Integer() {1}
jagged(1) = New Integer() {1, 2, 3}
C# Rectangular and jagged arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Choosing between them

Need Use
Size known, never changes, performance critical Array
Size changes, you add and remove List(Of T)
Fixed table of numbers Rectangular array
Rows of different length Jagged array
Lookup by key Dictionary

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In VB.NET, how many elements does Dim a(9) As Integer create?

    The number is the upper bound, so indexes 0 through 9 exist: ten elements.
  2. 2. What does ReDim Preserve do when growing an array?

    It allocates a new array and copies; other references to the old array are not updated.
  3. 3. Which type is best when you keep adding items and do not know the final count?

    List(Of T) grows automatically and makes Add cheap on average.
  4. 4. A binary search on an array requires that the array is...

    Binary search halves the range each step, which only works on sorted data.

Summary

  • A VB array declaration gives the upper bound; Length is bound plus one.
  • Arrays are fixed size; ReDim Preserve copies into a new array.
  • List(Of T) grows for you and offers Add, Insert, Remove, Sort, Find.
  • Rectangular arrays have one shape; jagged arrays hold rows of varying length.
  • Binary search needs sorted input.

Next: Dictionaries, Sets and Queues