Home > .NET > And vs AndAlso & Or vs OrElse

And vs AndAlso & Or vs OrElse

When we are programming we search for tricks or logic in our code to save milliseconds of time and to make our code compiled faster and smarter.
.NET gives us many features to make our code compiled faster, and one of these features is the implementation of a two additional operators: AndAlso & OrElse. You might already had heard about these two operators but didn’t know exactly what is the difference they offer over And & Or, in this post I will explain exactly what is the difference and when to use them.

These two new operators follow a new concept called Short-circuit evaluation, which means that If the first part of an AndAlso operator in an If statement evaluates to False, the second part is not evaluated. Similarly, if the first part of an OrElse operator in an If statement evaluates to True, the second operand is not evaluated.
So by using these two operators:

  • You can optimize your code by not executing any more of a compound expression than required (as I mentioned above, it will cause less execution time for your code).
  • You can avoid executing part of your code statement to avoid exceptions. For example:
        If str IsNot Nothing And str.Contains("ms") Then
           ' code statement
        End If

The above statement will throw an exception if str is nothing. But using AndAlso will solve the problem:

        If str IsNot Nothing AndAlso str.Contains("ms") Then
           ' code statement
        End If

Since str is Nothing, the second part of your If statement will not be executed.

Another good example can be when we want to divide a/b, we should check first if b IsNot zero so that we avoid another exception.
Off course all these examples can be used with OrElse when the first part of your code statement is true, so the second part will not be executed as well.

One more thing to mention is that AndAlso & OrElse are best practice to be used when you don’t want to evaluate the whole statement of your code, so if you have a function call in the second part that you need to call either way then you have to go back to And & Or since when using them all your code statement will be executed.

  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: