2

Please take a look at the following code:

Try
  Dim Reader As New System.IO.StreamReader(PositionsFileName)
  Do While Reader.Peek() <> -1
    Dim Positions() As String = Reader.ReadLine().Split("|")
    If (Positions(0) Is Nothing) Or (Positions(1) Is Nothing) Or (Positions(2) Is Nothing) Then
      ' something
    End If
  Loop
Catch ex As Exception
  ex.Source = Nothing
End Try

I am reading a file and expecting format something|something1|something2. I am trying to make it set "Nothing" to the array index which does not exists (the file format is broken), so that the If statement goes smoothly, but it seem I am doing it wrong. Can you give me some hints?

2
  • How many "Somethings" will it read? You can do If Position.lenght() = 0 to know if split was sucessful. Commented Oct 26, 2012 at 1:08
  • You should remove your Catch ex As Exception. It isn't really helping you to write better code and just hides errors. Commented Oct 26, 2012 at 1:26

3 Answers 3

1

If you do Split("|") and there are only 2 items (for example, something|something1), Positions(2) will not be Nothing, it will just not be there. So your code will raise an exception, something about index out of bounds of the array.

If you need Positions(2) contain Nothing in this case, you code can look like this:

Dim Positions(2) As String
Dim tmpArray() As String = Reader.ReadLine().Split("|")
For i = 0 To UBound(Positions)
  If i <= UBound(tmpArray) Then
    Positions(i) = tmpArray(i)
  Else
    Positions(i) = Nothing
  End If
Next
Sign up to request clarification or add additional context in comments.

2 Comments

That is why I want that exception to be catched and "Nothing" to be set to the Position(2) so the If statement fails. How to set that value? What about the ex.Source = Nothing is wrong?
@barakuda28: ex.Source = Nothing will not help you set Position(2) = Nothing. See my edit for a possible solution.
1

I assume that you only have three "Somethings" per valid line. If so, try writing your Positions() assignment like this:

Dim Positions() As String = Reader _
    .ReadLine() _
    .Split("|") _
    .Concat(Enumerable.Repeat("Nothing", 3)) _
    .Take(3) _
    .ToArray()

This will ensure that you have three items every time. No need to check for nothings.

Comments

1

Just check positions.length after the split. Also, if you want to check for cases like "||Something2|Something3", the first position will be "" not Nothing. The orelse is a shortcircuit that will keep the latter condtitions from being evaulated if an earlier condition is met.

If Positions.length < 3 OrElse Positions(0) = "" OrElse Positions(1) = "" OrElse Positions(2) = "" Then
  ' something
End If

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.