Common Cures for Ailments Part 3 ' Using AndAlso

One of the things I struggled with early in my coding career and have probably hung onto way too long is the use of some nested if calls. The classic example of the way I have implemented this structure is checking to see if an object exists, then checking to see if a property or value is equal to something. A classic example from some of my 1.0/1.1 .NET code might be checking for the value of a string.

       

Dim

s

As

String

 

       

Public

Function

GetSValue()

As

String

           

If

Not

IsNothing(s)

Then

               

If

s.Length > 0

Then

                   

Return

s

               

Else

                   

Return

""

               

End

If

           

End

If

       

End

Function

I chose this example because the .NET 2.0 version of the String class contains a very useful property, IsNullOrEmpty that performs this test for us and returns a Boolean value. There is nothing wrong with the coding pattern I chose to utilize back in the day and it has become a second nature thing for me to check things this way. But as with everything in .NET there is a better way to perform this classic test by using AndAlso.

       

Public

Function

GetSValue()

As

String

           

If

Not

IsNothing(s) =

False

AndAlso

s.Length > 0

Then

               

Return

s

           

Else

               

Return

String

.Empty

           

End

If

       

End

Function

This is a little more efficient and performs the exact same test, except it uses 1 If statement instead of two, making it easier to manage. The reason I had chosen the first format is calling a property or method on an object that has not been instantiated at the time of the call will cause a Null Reference exception. The AndAlso operator checks the value of the first expression, if it is false then it does not evaluate the second expression. This makes it perfect to check the value of a member of an object and verify it exists first.

The AndAlso operator is a VB only item, but you can just as easily perform the test in C#. The same method would in C# would utilize the || operator and a wrapped first check.

       

public

string

GetSValue()

        {

       

if

((s != null) || s.Length > 0) {

          

return

s;

        }

else

{

          

return

string

.Empty;

        }

        }

You can even chain expressions using the AndAlso operator, as soon as the if statement finds a false expression it will stop checking and return False. If the statement completes the full test without any returning False, then it will return True. So please try to start integrating AndAlso statements into you code to save yourself some trouble maintaining your code and also making it execute just a little faster.

Share This Article With Your Friends!