user4851317
user4851317

Reputation:

Use ReDim for unknown size of array

I am currently reading and splitting a file's data into 2 arrays (name and age). I have created them both as arrays of unknown size. This is because I might add lines to my data file, but if I dim them in this way (e.g.name()), an error occurs. However I am unsure of how to use ReDim in this situation.

Dim o As Integer
Dim name() as string
Dim age() as integer

r = New System.IO.StreamReader("C:\Users\files\names.txt")
While r.Peek() <> -1
    v = r.ReadLine()
    temperary = v.Split(".")
    name(o) = temp(0)
    age(o) = temp(1)
    o = o + 1
End While
r.Close()
Catch ex As Exception
    Me.Close()
End Try

Upvotes: 0

Views: 144

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460108

You don't need ReDim, use a List(Of String) and if you finally need an array, use ToArray:

Dim names As New List(Of String)
Dim ages As New List(Of String)
r = New System.IO.StreamReader("C:\Users\files\names.txt")

While r.Peek() <> -1
    v = r.ReadLine()
    temp = v.Split(".")
    names.Add(temp(0))
    ages.Add(temp(1))
    o = o + 1
End While
' if you need arrays use names.ToArray() and/or ages.ToArray()

But i would use a List(Of User) instead where User is a class that you have to create which has at least two properties Name and Age.

Upvotes: 1

Related Questions