-1

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?

Skitzafreak
  • 1,387
  • 4
  • 22
  • 39
  • 1
    Use `String.IsNullOrEmpty(Supplier)` – Tim Schmelter Jun 22 '18 at 12:53
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – zaggler Jun 22 '18 at 13:07
  • Possible duplicate of [(OrElse and Or) and (AndAlso and And) - When to use?](https://stackoverflow.com/questions/8409467/orelse-and-or-and-andalso-and-and-when-to-use) – Visual Vincent Jun 22 '18 at 13:48

2 Answers2

4

Change it to:

If IsNothing(Supplier) OrElse Supplier.Equals("") Then

Your previous expression means that Supplier.Equals("") gets evaluated regardless of whether the first half of the statement is true. Thus, it gets evaluated and produces an error.

The OrElse piece means if the first half is true the second half is not evaluated at all. A language construct.

Ctznkane525
  • 6,748
  • 2
  • 13
  • 36
0

If supplier is Nothing then you can't compare it with the empty string, and both statements will be evaluated even if the first is already false.

  • I'm not sure what you mean by "can't compare it to empty string", but the reason both expressions are evaluated is because of the operator used. `Or` does a bitwise comparison and `OrElse` does a logical short-circuiting comparison and won't evaluate the second if the first was true. See this https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/orelse-operator for more information. – Fabulous Jun 22 '18 at 13:12
  • If Supplier is nothing, can't compare it with "", and that is where the null reference exception is coming. – Alessandro Mandelli Jun 22 '18 at 13:46
  • 1
    I get you now. `IsNullOrEmpty` exists for such cases – Fabulous Jun 22 '18 at 13:50