vendredi 22 juin 2018

Why am I getting this NullObjectReference exception?

I am working on a program in VB.Net and I am having some errors pop up at run time that I don't quite understand. First off, I shall show you the code block I am getting my exception thrown at:

Public Sub AddPartToOrder(ByVal partNum As String, ByVal quantity As Integer)
    Using dbContext As New Data_LINQDataContext
        If IsNothing(Supplier) Or Supplier.Equals("") Then
            'Code here
        End If
    End Using
End Sub

The exception is getting thrown at the If statement, with Supplier being a NullReferenceException. Now when I change the code to:

Public Sub AddPartToOrder(ByVal partNum As String, ByVal quantity As Integer)
    Using dbContext As New Data_LINQDataContext
        If IsNothing(Supplier) Then
            'Code here
        ElseIf Supplier.Equals("") Then
            'More Code here
        End If
    End Using
End Sub

The exception goes away. My question is, why I am getting the exception in the first instance but not the second? Doesn't the first If statement only check the second condition if the first one is false? Shouldn't it work the same way as the If/ElseIf?

Aucun commentaire:

Enregistrer un commentaire