Brandon Brandon - 9 months ago 56 Question

List(of String) or Array or ArrayList

Hopefully a simple question to most programmers with some experience.

What is the datatype that lets me do this?

Dim lstOfStrings as *IDK*
Dim String0 = "some value"
Dim String1 = "some value"
Dim String2 = "some value"
Dim String3 = "some value"

lstOfStrings.add(String0, String1, String2, String3)

I would access these like this

Dim s1 = lstOfStrings(0)
Dim s2 = lstOfStrings(1)
Dim s3 = lstOfStrings(2)
Dim s4 = lstOfStrings(3)

if I use List(of String)
I am only able to .add one thing to the list, and in my function I want to be able to store several values.


Private Function Foo() As List(Of String)

Dim temp1 As String
Dim temp2 As String
Dim temp3 As String

Dim temp4 As String
Dim temp5 As String
Dim temp6 As String

Dim inputs() As String = {temp1, temp2, temp3, temp4, temp5, temp6}

Dim lstWriteBits() As List(Of String) = New List(Of String)(inputs)

Return lstWriteBits
End Function

Answer Source

List(Of String) will handle that, mostly - though you need to either use AddRange to add a collection of items, or Add to add one at a time:


If you're adding known values, as you show, a good option is to use something like:

Dim inputs() As String = { "some value", _
                              "some value2", _
                              "some value3", _
                              "some value4" }

Dim lstOfString as List(Of String) = new List(Of String)(inputs)

' ...
Dim s3 = lstOfStrings(3)

This will still allow you to add items later as desired, but also get your initial values in quickly.


In your code, you need to fix the declaration. Change:

Dim lstWriteBits() As List(Of String) 


Dim lstWriteBits As List(Of String) 

Currently, you're declaring an Array of List(Of String) objects.