String
List
Often in VB.NET programs we want to store multiple Strings together. These can be string
literals, or dynamically-created strings. We can do this with a String
List
.
By creating a special kind of List
, we can store and access just Strings. The List
is a generic type, so we specify its type with the keywords "Of String
."
In VB.NET programs we usually need to place Strings onto a List
with the Add()
function. We can do this at any point in the program.
String
List
with the "Of String
" keywords on the type. We call Add()
3 times.string
dynamically by calling ToString()
on an Integer. This string
can also be placed into the String
List
.String
List
. Note we must subtract 1 from the Count
to stay in range.For Each
loops if we just want to access each element in a List
.Module Module1 Sub Main() ' Step 1: create new List and Add 3 strings to it. Dim values = New List(Of String) values.Add("one") values.Add("two") values.Add("THREE") ' Step 2: we can add strings that are not literals. Dim test = 100.ToString() values.Add(test) ' Step 3: use For to iterate over indexes of string list. For i = 0 to values.Count - 1 ' Get element. Dim value = values(i) ' Display with string interpolation syntax. Console.WriteLine($"Value {i}: {value}") Next ' Step 4: use For Each to access elements in string list more safely. For Each value in values If char.IsUpper(value(0)) Console.WriteLine($"Uppercase: {value}") End If Next End Sub End ModuleValue 0: one Value 1: two Value 2: THREE Value 3: 100 Uppercase: THREE
String
List
optimizationsIn older VB.NET programs, we needed to cast values from an ArrayList
, but the List
type does not require casting. Each String
is returned ready-to-use.
Many VB.NET programs will require the String
List
, and using this construct, as well as the List
generic with other types, is essential.