Search code examples
vb.netshort-circuiting

What is the difference between And and AndAlso in VB.NET?


In VB.NET, what is the difference between And and AndAlso? Which should I use?


Solution

  • The And operator evaluates both sides, where AndAlso evaluates the right side if and only if the left side is true.

    An example:

    If mystring IsNot Nothing And mystring.Contains("Foo") Then
      ' bla bla
    End If
    

    The above throws an exception if mystring = Nothing

    If mystring IsNot Nothing AndAlso mystring.Contains("Foo") Then
      ' bla bla
    End If
    

    This one does not throw an exception.

    So if you come from the C# world, you should use AndAlso like you would use &&.

    More info here: http://www.panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/