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.
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
.
List
generic collection, and then call Add()
4 times to add the first 4 prime numbers.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
exampleConsider this example, where we specify a custom Class
with 2 fields in it. We then create Class
instances and pass them to Add.
List
. We specify the type Test to indicate we want Test objects in the list.Add()
3 times, and in each call, we create a new Test instance by invoking the New function.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
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.