Question array initialization, way simple

jamie123

Well-known member
Joined
May 30, 2008
Messages
82
Programming Experience
Beginner
I dont' know why I can't figure this out, but I don't wanna spend anymore time on it and I know someone knows the answer here. Very simple question. Here's my code:

VB.NET:
  Dim companyids(200) As String

     myReader = File.OpenText(ComboBox1.Text + "SPE\DI_IR.upc")
                For i As Integer = 1 To diskdirlines
                    companyids(i) = myReader.ReadLine().Substring(2, 4)
                Next

I don't want to dim companyids with an index of 200, I would like it to only initialize as many elements as it needs. But I can't figure out how to initialize it without putting in all of the elements at once (impossible, it must run through that loop) or putting in a static index like I have done above. How can I initialize this array so that its number of elements is dynamic and can change everytime?

Thanks!
 
I'm not sure I understand your problem, so here's my best answer to what I think you're asking...

First when you initialize the string array companyids with 200, you are actually creating an array of 201 elements -- arrays are zero based so you've created elements 0 to 200 or 201 all together. You can create a dynamic array that can be changed during runtime like this:

Dim companyids() as String

then prior to using the array you can re-dimension it and load it like this:

myReader = File.OpenText(ComboBox1.Text + "SPE\DI_IR.upc")
ReDim companyids(diskdirlines - 1)
For i As Integer = 0 To diskdirlines - 1
companyids(i) = myReader.ReadLine().Substring(2, 4)
Next

This way the array companyids can be whatever size it needs to be to accommodate your needs.
 
It is better if you use a list, it is a dynamic array. If the size is known ReDim statement could be better.
VB.NET:
Dim companyids As New List(Of String)
Do Until myReader.EndOfStream
    companyids.Add(myReader.ReadLine().Substring(2, 4))
Loop
You can also instead read all lines and convert them:
VB.NET:
Dim companyids() As String = IO.File.ReadAllLines("data.txt")
For i As Integer = 0 To companyids.Length - 1
    companyids(i) = companyids(i).Substring(2, 4)
Next
This can be simplified with VB 2008:
VB.NET:
Dim companyids() As String = Array.ConvertAll(IO.File.ReadAllLines("data.txt"), Function(x) x.Substring(2, 4))
 
Back
Top