Background
The List(Of T) collection was introduced in VB.NET to replace outdated collections, providing type safety, dynamic resizing, and fast indexed access to elements. Using a list allows for data structuring, working with typed elements, and avoiding common errors associated with non-generic collections.
Problem
Beginners often do not understand how to correctly access elements of a list, how to add, modify and remove elements, and what happens with incorrect index usage (for example, going out of bounds). This leads to exceptions during program execution.
Solution
In List(Of T), elements are indexed starting from zero. Access to an element is performed by index for both reading and writing. If the index is invalid, an ArgumentOutOfRangeException is thrown. The collection methods allow for safe manipulation of elements:
Code example:
Imports System.Collections.Generic Dim numbers As New List(Of Integer)() numbers.Add(10) numbers.Add(20) Dim first As Integer = numbers(0) ' Get element at index 0 numbers(1) = 99 ' Set element at index 1 ' Deletion numbers.RemoveAt(0) ' Remove by index
Key Features:
If we access an index that equals the number of elements in List(Of T), will we get the last element?
No. Indexing starts at 0, and the maximum valid index is (Count - 1). Accessing an index equal to Count will result in an ArgumentOutOfRangeException.
Is it possible to add an element in the middle of List(Of T) without removing existing data?
Yes, by using the Insert method:
numbers.Insert(1, 42) ' Will insert 42 at the second position, shifting others to the right.
Is it dangerous to modify List(Of T) while iterating using For Each?
Yes, it is dangerous. This will lead to InvalidOperationException. For such operations, use For with index or first prepare a list for removal.
In the program, List(Of T) is iterated using For Each and elements are removed inside the iteration.
Pros:
Cons:
The code iterates elements from end to start using For and removes suitable objects.
Pros:
Cons: