|
-
Jun 29th, 2005, 09:34 PM
#1
And/Or vs AndAlso/OrElse
Here I am again, although with a less interesting topic this time.
I've noticed that a great many people seem to use And and Or by default, rather than AndAlso and OrElse. In most cases it doesn't really matter, but I think it is because many people don't understand the difference, rather than by design or even laziness. Personally, I never use And or Or unless I specifically need to, i.e. I use AndAlso and OrElse by default.
Although it will generally make only a microscopic difference, it is more efficient to use AndAlso and OrElse because they use short-circuiting, meaning that they only evaluate the second condition if it is needed. I would generally only use And and Or if the second expression was a function that needed to be executed whether the first expression was true or not.
As I said, in the majority of cases there will be no noticeable difference. I mention it because if beginners get in the habit of using And and Or by default then there will be times that they get errors that they do not understand. For those who aren't sure, take the following example where you only want to create a particular form if it doesn't already exist.
Code:
Dim myChild As ChildForm
Private Sub ShowChild()
If Me.myChild Is Nothing OrElse Me.myChild.IsDisposed Then
Me.myChild = New ChildForm
Me.myChild.Show()
Else
Me.myChild.Activate()
End If
End Sub
Code:
Dim myChild As ChildForm
Private Sub ShowChild()
If Me.myChild Is Nothing Or Me.myChild.IsDisposed Then
Me.myChild = New ChildForm
Me.myChild.Show()
Else
Me.myChild.Activate()
End If
End Sub
The first example will work correctly, while the second example will throw a NullReferenceException if the form has not been instantiated because it tries to evaluate Me.myChild.IsDisposed on a null reference.
The moral of the story is this: make the extra four key presses and use AndAlso and OrElse by default to avoid the possibility of an unnoticed error. Only use And and Or when you specifically need to.
Last edited by jmcilhinney; Mar 26th, 2011 at 07:46 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|