开发者

Searching though an empty jagged array in VB.NET

So I have a function that looks up values in a jagged array, and it goes like this:

Private Function Lookup(ByVal Search_path As String) As Integer
    Dim i As Integer = 0
    Do Until MasterIndex(i) Is Nothing 'throws an exception here
        If Search_path = MasterIndex(i)(0) Then
            Return MasterIndex(i)(1)
        End开发者_StackOverflow社区 If
        i = i + 1
    Loop
    Return -1
End Function

Problem is, when I test this with an empty array, it gives me the error of Index was outside the bounds of the array at line 3. How do I fix this?


You need to check to see if your indexer exceeds the number of elements in the array.

Private Function Lookup(ByVal Search_path As String) As Integer
    Dim i As Integer = 0
    Do Until i = MasterIndex.Length OrElse MasterIndex(i) Is Nothing
        If Search_path = MasterIndex(i)(0) Then
            Return MasterIndex(i)(1)
        End If
        i = i + 1
    Loop
    Return -1
End Function


Arguably cleaner as a FOR loop:

Private Function Lookup(ByVal Search_path As String) As Integer 
  for i = 0 to MasterIndex.Length - 1 
    if MasterIndex(i) is nothing then exit for
    If Search_path = MasterIndex(i)(0) Then 
        Return MasterIndex(i)(1) 
    End If 
  next
  Return -1 
End Function 

Endlessly debatable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜