Re-use a dynamic array created for string.split for another string.split task?

22-degrees

Well-known member
Joined
Feb 11, 2012
Messages
156
Location
South East Ireland
Programming Experience
1-3
I'm working with a large amount of csv data and I am utilizing string.split

The arrray to hold the values is created like so:

VB.NET:
Dim tmpArray() as string = readline.split(",")

Once I have done what I need to with the values stored in tmpArray, I need to move on and split more data.

Is there a way I can re-use the tmpArray array in the same sub to store another batch of split data rather than creating another dynamic array?

This feels like a very noobish question but google search did not help me much so I think I am missing a keyword here..
 
You're not creating the array in the first place. You're declaring the 'tmpArray' variable but it is Nothing at that stage. Just because you build a garage doesn't mean that you have a car. It is the Split method that creates the array object and returns it. You are assigning that return value to your variable. If you want to call Split again on another String then the same thing will happen, i.e. it will create return a String array object. Most likely you would want to assign it to the same variable, but it's still a different array object. You can drive one car out of your garage and then drive another one in. Your code could look like this:
VB.NET:
Dim fields As String()

Using reader As New StreamReader(filePath)
    Do Until reader.EndOfStream
        fields = reader.ReadLine().Split(","c)

        'Use fields here.
    Loop
End Using
or it could look like this:
VB.NET:
Using reader As New StreamReader(filePath)
    Do Until reader.EndOfStream
        Dim fields = reader.ReadLine().Split(","c)

        'Use fields here.
    Loop
End Using
Both will work and the compiler will optimise them to basically the same final code anyway. It's actually more appropriate to use the second option unless you specifically need to use the variable outside the loop. Good practice dictates that everything be declared with the narrowest scope possible.
 
Thanks,

Looks good and I feel better using it. I need to use the variable outside the loop so option 1 appealed more to me this time.

Once again, thanks for the analogy.. I'll get up to speed on terminology soon enough.
 
Back
Top