Jump to content
Xtreme .Net Talk

Recommended Posts

  • Administrators
Posted

Both AndAlso and OrElse (that sounds weird read out loud) give a performance benefit by only evaluating the minimum number of arguments.

 

e.g.

given the following 2 simple functions

   Private Function Test1() As Boolean
       MessageBox.Show("Test1")
       Return False
   End Function

   Private Function Test2() As Boolean
       MessageBox.Show("Test2")
       Return True
   End Function

 

if called from an if statement like

       If Test1() And Test2() Then
           MessageBox.Show("Both true")
       End If

you should get both the messageboxs from Test1 and Test2 displayed - despite the fact that because Test1 returns false the overall result can never be true.

 

Changing the if statement to

       If Test1() AndAlso Test2() Then
           MessageBox.Show("Both true")
       End If

you only get the first messagebox as it realises the result will always be false so there is no reason to even evalute the second condition.

 

However if Test2 performed some required functionality then that would also be skipped - this is the only time you would need to avoid AndAlso; however I would personally class that as a bad coding style anyway - relying on side-effects like that to get required code to execute is hard to debug / maintain and gives no real benefit.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...