Home
VB.NET
String List Example
This page was last reviewed on Nov 16, 2023.
Dot Net Perls
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."
List
Example. 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.
Step 1 We create our String List with the "Of String" keywords on the type. We call Add() 3 times.
Step 2 We create a string dynamically by calling ToString() on an Integer. This string can also be placed into the String List.
Step 3 We use For to iterate over the indexes in the String List. Note we must subtract 1 from the Count to stay in range.
Step 4 It is usually better to use 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 Module
Value 0: one Value 1: two Value 2: THREE Value 3: 100 Uppercase: THREE
String List optimizations. In 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.
ArrayList
And This leads to both clearer code, and faster code, as no overhead from handling Objects is needed.
Summary. Many VB.NET programs will require the String List, and using this construct, as well as the List generic with other types, is essential.
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 16, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.