If I place a breakpoint at the line currentrow = MyParser.ReadFields(), currentrow still contains the values of the previous line parsed from the file. After
currentrow = MyParser.ReadFields() executes, the current file line values are stored.
Since currentrow is declared inside the While loop, shouldn’t the previous currentrow value be out of scope when re-entering the While loop? Why does currentrow still retain values from the last line in the file?
Do I need to change Dim currentrow As String() to
Dim currentRow() = New String() {}? Why?
If File.Exists(filename) Then
Using MyParser As New FileIO.TextFieldParser(filename)
MyParser.TextFieldType = FileIO.FieldType.Delimited
MyParser.SetDelimiters("~")
While Not MyParser.EndOfData
Try
Dim currentrow As String()
'at this point, currentrow still contains prev values
currentrow = MyParser.ReadFields()
Catch
End Try
End While
End Using
End If
Because you have only declared the loop variable, as against this which results in a correct value of
Nothingon every iteration:or even better
“Dim” by itself, without the explicit initialization, will be optimized out as redundant.
Even if you assign
Nothing, it will always be reset toNothingon every iteration. If you only declare the variable it will always contain the “wrong” old value even if you would useConsole.WriteorMessageBox.Showafterwards.So always assign a default value in a loop variable to avoid side-effects.
Sidenote C# avoids this error source with the compiler warning CS0165: Use of unassigned local variable ‘variablename’.
So if you would try to use that unassigned variable before it gets assigned you would not even be able to compile with C#. I don’t know why VB.NET allows it.