Search code examples
vb.netoopobject-referencedo-loops

Object reference not set to an instance of an object? VB.NET


I have this code here:

Dim MasterIndex As String()()

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

Which gives me the error Object reference not set to an instance of an object occuring on the Do Until line. Why is this? How can I fix this?


Solution

  • The MasterIndex variable is never assigned that is why you have the exception

    You should instantiate MasterIndex first by calling the New() constructor:

     Dim MasterIndex As new String()()
    

    and fill it with data before calling the Lookup function.

    Something like:

     Private MasterIndex As String()() = New String()() {New String() {"A1", "A2"}, New String() {"B1", "B2"}}