Add. In VB.NET programs, we can sometimes create and use Lists with all their elements initialized at once. But usually we must call Add() to place more elements at the end.
With List Add, we must pass an argument of the correct type, and it is added to the end (appended) to the List. We can use Add() with Integers, Strings, and even custom Class instances.
Integer example. Consider this first example—we want a List of prime numbers. We represent these prime numbers as Integers, and use Add() to append them to the List.
Step 1 We create the List generic collection, and then call Add() 4 times to add the first 4 prime numbers.
Step 2 We use a For Each loop over the list to display the elements with in. We call Console.WriteLine.
Module Module1
Sub Main()
' Step 1: add some primes to the list.
Dim list = New List(Of Integer)
list.Add(2)
list.Add(3)
list.Add(5)
list.Add(7)
' Step 2: print all the primes in the list.
For Each value in list
Console.WriteLine(value)
Next
End Sub
End Module2
3
5
7
Class example. Consider this example, where we specify a custom Class with 2 fields in it. We then create Class instances and pass them to Add.
Step 1 We create a new List. We specify the type Test to indicate we want Test objects in the list.
Step 2 We call Add() 3 times, and in each call, we create a new Test instance by invoking the New function.
Step 3 After calling Add 3 times, we have 3 objects in the List, and we can use them in any way.
Module Module1
Class Test
Private _a as Integer
Private _b as Integer
Public Sub New(a as Integer, b as Integer)
_a = a
_b = b
End Sub
End Class
Sub Main()
' Step 1: create new List.
Dim list = New List(Of Test)
' Step 2: invoke the Add method 3 times and create objects to place in the list.
list.Add(New Test(1, 2))
list.Add(New Test(3, 4))
list.Add(New Test(5, 6))
' Step 3: there are now 3 objects in the list.
Console.WriteLine("DONE: {0}", list.Count)
End Sub
End ModuleDONE: 3
Summary. It is possible to append elements to a List any time after it was created. Lists are designed to grow their capacity as needed, so Add() is almost always safe to call.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 13, 2023 (edit).