Difference between And (&) and AndAlso(&&) in VB.net/C#.net

The ‘And'(&) operator evaluates both sides, where ‘AndAlso'(&&) only evaluates the right side 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.

================================================================================================

And operator will check all conditions in the statement before continuing, whereas the Andalso operator will stop if it knows the condition is false. For example:

if x = 5 And y = 7

Checks if x is equal to 5, and if y is equal to 7, then continues if both are true.

if x = 5 Andalso y = 7

Checks if x is equal to 5. If it’s not, it doesn’t check if y is 7, because it knows that the condition is false already. (This is called short-circuiting)

Generally people use the short-circuiting method, because it saves on runtime. However, if the second action (in this case y = 7) has a side effect that you want to run whether the first is true or not, i.e.:

if x == 5 And Object.Load()

Then you might want to use And. The reason you might want to use Andalso would be in the case where you want to make sure an object exists before performing an action on it:

if not Object is nothing Andalso Object.Load()

If that used And instead of Andalso, it would still try to Object.Load() even if it were nothing, which would throw an exception.

================================================================================================

If Not IsNull(myObj) Andalso myObj.SomeProperty = 3 Then
   ...
End If

Using the old And in the above expression would throw a NullReferenceException if myObj were null.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s