ANDALSO-ORELSE Simplicity.

Navneet HegdeNavneet (navneethegde)
CERTIFIED EXPERT
Published:
This is one of the simple operators yet less used due to clarity over its purpose. Let’s looks at it
1.ANDALSO :

Take an example where we are evaluating the business logic.

 Img1
Output
 
Img2
Case 1: In this case program will execute the IsValidUser function, it returns valid and then execute the HasAccessToUpdateOrders function which is false and everything is ok.

Case 2. Consider  here IsValidUser returns false then logically there is no way  that user might have any Access to update Orders, however the programs still executes the function  HasAccessToUpdateOrders. Logically this should have been avoided, unnecessary execution consuming resources and time.  Hence when we use AND both sides of expression will be executed before considering the final result.

So to avoid this we have short-circuiting, so now the same stuff with ANDALSO. And the output seems to evaluate only the first part since it’s false it doesn’t evaluate the second expression and improves the performance.

Img3
Output:
 
Img4
2. ORELSE:

Taking same example from above but instead of IsUser we consider IsAdmin, so if user is Admin then he should have access to update orders no need to check further.

 Img5
Output:
 
Img6
Case 3: In this case program will execute the IsAdmin function, it returns false and then execute the HasAccessToUpdateOrders function which is true and everything is ok.

Case 4: Consider  here IsAdmin returns true then logically  user have all access to update Orders, however the programs still executes the function  HasAccessToUpdateOrders. Logically this should have been avoided, unnecessary execution consuming resources and time.  Hence when we use OR both sides of expression will be executed before considering the final result.

So to avoid this we have short-circuiting, so now the same stuff with ORELSE. And the output seems to evaluate only the first part since it’s true it doesn’t evaluate the second expression and save redundant expression evaluation.

 Img7
Output:

 Img8
C# Equivalent:
AndAlso  && (C# Equivalent)
OrElse     ||   (C# Equivalent)

Conclusion :
AndAlso & OrElse can help improve performance by avoiding unnecessary code execution or database hits.
It can also be used to check if object is null, to avoid runtime errors.
Ex:
If Not myObject  Is Nothing AndAlso myObject.Count Then…

Open in new window

0
2,589 Views
Navneet HegdeNavneet (navneethegde)
CERTIFIED EXPERT

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.